using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Configuration;
using Org.BouncyCastle.Asn1.X509;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Transactions;
using WCS.Infrastructure.Attr;
using WCS.Infrastructure.Dto.Common;
using WCS.Infrastructure.Dto.Enums;
using WCS.Infrastructure.Dto.Models.Order;
using WCS.Infrastructure.Dto.Request.Epaylinks;
using WCS.Infrastructure.Dto.Request.Log;
using WCS.Infrastructure.Dto.Request.Order;
using WCS.Infrastructure.Dto.Request.Organization;
using WCS.Infrastructure.Dto.Request.Payment;
using WCS.Infrastructure.Dto.Request.ReportForm;
using WCS.Infrastructure.Dto.Request.User;
using WCS.Infrastructure.Dto.Response.Common;
using WCS.Infrastructure.Dto.Response.Epaylinks;
using WCS.Infrastructure.Dto.Response.Order;
using WCS.Infrastructure.Dto.Response.Payment;
using WCS.Infrastructure.EFCore;
using WCS.Infrastructure.IOC;
using WCS.Infrastructure.Tools;
using WCS.Repository.Interface;
using WCS.Service.EFCore;
using WCS.Service.Interface;

namespace WCS.Service.Instance
{
    [Inject]
    public class PaymentService : BaseService, IPaymentService
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IConfiguration _configuration;
        private readonly PaymentIOC _paymentIOC;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ICouponService _couponService;
        private readonly ILogService _logService;
        private readonly IUserService _userService;
        private readonly EpaylinksService epaylinksService;
        public PaymentService(IConfiguration configuration, PaymentIOC paymentIOC, IHttpContextAccessor httpContextAccessor,
            ICouponService couponService, ILogService logService, IUnitOfWork unitOfWork, IUserService userService)
        {
            _configuration = configuration;
            _paymentIOC = paymentIOC;
            _httpContextAccessor = httpContextAccessor;
            _couponService = couponService;
            epaylinksService = new EpaylinksService(_configuration, _httpContextAccessor);
            _logService = logService;
            _unitOfWork = unitOfWork;
            _userService = userService;
        }


        /// <summary>
        /// 新增交易订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddOrdersAsync(OrderCreateRequestDto dto)
        {
            try
            {
                await _unitOfWork.BeginTransactionAsync(System.Data.IsolationLevel.ReadCommitted);
                OrderRequestDto orderDto = new OrderRequestDto();
                orderDto.OrderAmount = dto.OrderAmount;
                orderDto.CodeId = dto.CodeId;
                orderDto.CouponInstanceId = dto.CouponInstanceId;

                var paymentCode = await _paymentIOC._paymentCodeEFCore.QueryAll(d => d.Id == orderDto.CodeId).FirstOrDefaultAsync();
                if (paymentCode != null)
                {
                    if (paymentCode.EnableStatus == 0)
                    {
                        return GetResult(message: "该收款码已被禁用，无法支付！请更换");
                    }
                    if (paymentCode.IsDeleted)
                    {
                        return GetResult(message: "该收款码已被失效，无法支付！请更换");
                    }
                }
                else
                {
                    return GetResult(message: "该收款码无法正常支付！请更换");
                }


                string orderId = Config.GUID();
                if (!string.IsNullOrEmpty(orderDto.CouponInstanceId))
                {
                    string userId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                    orderDto.UserId = userId;
                    var couponConsumptionRecordResult = await _couponService.AddCouponConsumptionRecordAsync(new Infrastructure.Dto.Request.Coupon.CouponConsumptionRecordRequestDto
                    {
                        CouponInstanceId = orderDto.CouponInstanceId,
                        OrderId = orderId,
                        UserId = userId,
                        ConsumptionType = 3,
                        ConsumptionCodeId = orderDto.CodeId,
                    });

                    var calculateCouponInstanceResult = await _couponService.CalculateCouponInstanceAsync(new Infrastructure.Dto.Request.Coupon.CalculateCouponInstanceRequestDto
                    {
                        CouponInstanceId = orderDto.CouponInstanceId,
                        OrderAmount = orderDto.OrderAmount
                    });

                    if (couponConsumptionRecordResult.code == ApiCode.fail || calculateCouponInstanceResult.code == ApiCode.fail)
                    {
                        await _unitOfWork.RollbackAsync();
                        return GetResult(message: "优惠券使用失败，请稍后重试！");
                    }

                    var calculateCouponInstance = calculateCouponInstanceResult.data as Infrastructure.Dto.Request.Coupon.CalculateCouponInstanceRequestDto;
                    if (calculateCouponInstance != null)
                    {
                        orderDto.DiscountAmount = calculateCouponInstance.DiscountAmount;
                        orderDto.PayAmount = calculateCouponInstance.PayAmount;
                        orderDto.PlatformServiceFee = calculateCouponInstance.PlatformServiceFee;
                        orderDto.PlatformServiceFeeRate = calculateCouponInstance.PlatformServiceFeeRate;
                        orderDto.RecommendationCommissionAmount = calculateCouponInstance.RecommendationCommissionAmount;
                        orderDto.RecommendMerchantId = calculateCouponInstance.RecommendMerchantId;
                    }
                    else
                    {
                        await _unitOfWork.RollbackAsync();
                        return GetResult(message: "优惠券核销失败，请稍后重试！");
                    }
                }
                else
                {
                    orderDto.PayAmount = orderDto.OrderAmount;
                }

                // 如果实际收款金额小于等于0，则设置为0，并且平台服务费和推荐商户抽成金额也设置为0
                if (orderDto.PayAmount <= 0)
                {
                    orderDto.PayAmount = 0;
                    orderDto.PlatformServiceFee = 0;
                    orderDto.RecommendationCommissionAmount = 0;
                }


                Order order = new Order()
                {
                    Id = orderId,
                    OrderCode = Config.GenerateCode("ORD"),
                    OrderType = orderDto.OrderType,
                    CodeId = paymentCode.Id,
                    MerchantId = paymentCode.MerchantId,
                    StoreId = paymentCode.StoreId,
                    UserId = orderDto.UserId,
                    DividedAgreementId = paymentCode.DividedAgreementId,

                    OrderAmount = orderDto.OrderAmount,
                    CouponInstanceId = orderDto.CouponInstanceId,
                    DiscountAmount = orderDto.DiscountAmount,
                    PayAmount = orderDto.PayAmount,
                    PlatformServiceFee = orderDto.PlatformServiceFee,
                    PlatformServiceFeeRate = orderDto.PlatformServiceFeeRate,
                    Rate = 0.0035m,
                    RefundableAmount = orderDto.PayAmount,
                    PaymentStatus = 0,
                    ProcedureFee = 0,

                    CreationTime = DateTime.Now,
                    RecommendationCommissionAmount = orderDto.RecommendationCommissionAmount,
                    RecommendMerchantId = orderDto.RecommendMerchantId,

                };
                // 计算手续费（订单金额少于100分即1元RMB就不收取手续费或使用优惠券不收手续费）
                if (string.IsNullOrEmpty(orderDto.CouponInstanceId))
                    order.Commission = (long)(order.PayAmount < 100 ? 0 : Math.Ceiling((decimal)(order.PayAmount * order.Rate)));
                //计算结算金额
                order.SettlementAmount = order.PayAmount - order.Commission - orderDto.PlatformServiceFee;

                //计算结算日期
                int settlementCycle = 0;

                var store = await _paymentIOC._storeEFCore.QueryAll(d => d.Id == paymentCode.StoreId).FirstOrDefaultAsync();
                var merchant = await _paymentIOC._merchantEFCore.QueryAll(d => d.Id == paymentCode.MerchantId).FirstOrDefaultAsync();
                // 1. 首先查找收款码的结算周期
                if (paymentCode.SettlementCycle.HasValue && paymentCode.SettlementCycle.Value > 0)
                {
                    settlementCycle = paymentCode.SettlementCycle.Value;
                }
                else
                {
                    // 2. 如果收款码结算周期为0或null，查找门店的结算周期
                    if (store?.SettlementCycle.HasValue == true && store.SettlementCycle.Value > 0)
                    {
                        settlementCycle = store.SettlementCycle.Value;
                    }
                    else
                    {
                        // 3. 如果门店结算周期为0或null，查找商户的结算周期
                        if (merchant != null)
                        {
                            settlementCycle = merchant.SettlementCycle;
                        }
                    }
                }

                // 计算结算日期：当前时间 + 结算周期天数，只取日期部分
                order.SettlementDate = DateTime.Now.AddDays(settlementCycle).Date;

                //计算分账日期
                DividedAgreement dividedAgreement = null;
                if (!string.IsNullOrEmpty(order.DividedAgreementId))
                {
                    dividedAgreement = await _paymentIOC._dividedAgreementEFCore.QueryAll(d => d.Id == order.DividedAgreementId).FirstOrDefaultAsync();

                    if (dividedAgreement == null || !DividedService.IsAgreementEffective(dividedAgreement, DateTime.Now))
                    {
                        //return GetResult(message: "关联分账协议无效（已删除/未激活/未启用或不在有效期）");
                        order.DividedAgreementId = null;
                    }
                    else
                    {

                        if (dividedAgreement?.DividedCycle.HasValue == true)
                        {
                            // 分账日期 = 结算日期 + 分账周期天数，只取日期部分
                            order.DividedDate = order.SettlementDate.AddDays(dividedAgreement.DividedCycle.Value).Date;
                        }
                        var dividedAgreementDetails = await _paymentIOC._dividedAgreementDetailEFCore.QueryAll(d => d.DividedAgreementId == order.DividedAgreementId).ToListAsync();
                        var user = await _paymentIOC._sysUserEFCore.QueryAll(d => dividedAgreementDetails.Select(e => e.UserId).Contains(d.Id)).ToListAsync();

                        foreach (var dividedAgreementDetail in dividedAgreementDetails)
                        {
                            orderDto.OrderSnapshot.AgreementDetails.Add(new AgreementDetail
                            {
                                Name = user.Where(e => e.Id == dividedAgreementDetail.UserId).Select(e => e.Name).FirstOrDefault(),
                                Phone = user.Where(e => e.Id == dividedAgreementDetail.UserId).Select(e => e.Phone).FirstOrDefault(),
                                Ratio = dividedAgreementDetail.Ratio,
                            });
                        }
                    }
                }

                //记录订单快照
                orderDto.OrderSnapshot.Code = paymentCode?.Code;
                orderDto.OrderSnapshot.CodeName = paymentCode?.CodeName;
                orderDto.OrderSnapshot.StoreCode = store?.StoreCode;
                orderDto.OrderSnapshot.StoreName = store?.Name;
                orderDto.OrderSnapshot.MerchantCode = merchant?.MerchantCode;
                orderDto.OrderSnapshot.MerchantName = merchant?.Name;
                orderDto.OrderSnapshot.AgreementCode = dividedAgreement?.AgreementCode;
                orderDto.OrderSnapshot.AgreementName = dividedAgreement?.AgreementName;
                orderDto.OrderSnapshot.DividedCycle = dividedAgreement?.DividedCycle;
                orderDto.OrderSnapshot.SettlementCycle = settlementCycle;
                orderDto.OrderSnapshot.SnapshotTime = DateTime.Now;
                order.OrderSnapshot = Config.SerializeToJson<OrderSnapshotModel>(orderDto.OrderSnapshot);

                //易票联
                var outTradeNo = order.Id;
                string url = "";
                string sentent = "";
                var apiBaseUrl = _configuration["PaymentApi:BaseUrl"];


                if (dto.PayMethod == "6" || dto.PayMethod == "7")
                {
                    url = $"{apiBaseUrl}/api/txs/pay/UnifiedPayment";

                    order.OutTradeNo = outTradeNo;//商户订单号
                    order.NotifyUrl = $"{_configuration["SelfUrl"]}/api/Payment/ProcessPaymentResultNotification";//支付结果通知地址
                    order.Version = "3.0";//版本号
                    order.ClientIp = "";//用户终端IP
                    order.CustomerCode = "562294004495976";// 商户号
                    order.NoCreditCards = "false";// 是否禁用信用卡（花呗不能用）
                    order.AttachData = "attachData";// 商户备注
                    order.PayMethod = dto.PayMethod;//支付方式
                    order.PayCurrency = orderDto.PayCurrency;// 支持币种
                    order.RedirectUrl = dto.RedirectUrl ?? ""; // 支付通知结果前端跳转地址
                    order.AreaInfo = store?.Address ?? merchant?.Address ?? "440100";// orderDto.AreaInfo;//地区信息六位数

                    orderDto.OrderInfo.Id = outTradeNo;//商品订单编号
                    orderDto.OrderInfo.BusinessType = "100001"; // 业务类型
                    orderDto.OrderInfo.GoodsList.Add(new EpaylinksGoods { Amount = orderDto.PayAmount, Name = merchant?.Name, Number = "1" });//商品信息
                    order.OrderInfo = Config.SerializeToJson(orderDto.OrderInfo);

                    DateTime dtNow = DateTime.Now;
                    order.TransactionStartTime = dtNow.ToString("yyyyMMddHHmmss");//开始时间
                    order.TransactionEndTime = dtNow.AddMinutes(30).ToString("yyyyMMddHHmmss");//结束时间

                    order.NonceStr = Config.GenerateRandomKey(32);//随机字符串

                    sentent = "{\"areaInfo\":\"" + order.AreaInfo +
                        "\",\"attachData\":\"" + order.AttachData + "\",\"clientIp\":\"" + order.ClientIp + "\"," +
                        "\"customerCode\":\"" + order.CustomerCode + "\",\"needSplit\":false,\"noCreditCards\":" + order.NoCreditCards + ",\"nonceStr\":\"" + order.NonceStr + "\",\"notifyUrl\":\"" + order.NotifyUrl + "\"," +
                        "\"orderInfo\":" + order.OrderInfo + "," +
                        "\"payAmount\":" + order.PayAmount + ",\"payCurrency\":\"" + order.PayCurrency + "\",\"redirectUrl\":\"" + order.RedirectUrl + "\",\"transactionEndTime\":\"" + order.TransactionEndTime + "\"," +
                        "\"version\":\"" + order.Version + "\",";
                    sentent += "\"outTradeNo\":\"" + order.OutTradeNo + "\",\"transactionStartTime\":\"" + order.TransactionStartTime + "\"}";
                }

                if (dto.PayMethod == "1" || dto.PayMethod == "35")
                {
                    url = $"{apiBaseUrl}/api/txs/pay/WxJSAPIPayment";

                    string userId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                    var userMini = await _paymentIOC._sysUserMiniProgramEFCore.QueryAll(d => d.Id == userId).FirstOrDefaultAsync();
                    if (userMini == null)
                        return GetResult(0, "用户未登录");
                    order.Version = "3.0";//版本号
                    order.OutTradeNo = outTradeNo;//商户订单号
                    order.CustomerCode = "562294004495976";// 商户号
                    order.SubAppId = userMini.AppId;//子商户公众账号ID
                    order.OpenId = userMini.OpenId;
                    order.ClientIp = "";//用户终端IP

                    orderDto.OrderInfo.Id = outTradeNo;//商品订单编号
                    orderDto.OrderInfo.BusinessType = "100001"; // 业务类型
                    orderDto.OrderInfo.GoodsList.Add(new EpaylinksGoods { Amount = orderDto.PayAmount, Name = merchant?.Name, Number = "1" });//商品信息
                    order.OrderInfo = Config.SerializeToJson(orderDto.OrderInfo);

                    order.PayMethod = dto.PayMethod;//支付方式
                    order.PayCurrency = orderDto.PayCurrency;// 支持币种
                    order.NoCreditCards = "false";// 是否禁用信用卡（花呗不能用）
                    order.NotifyUrl = $"{_configuration["SelfUrl"]}/api/Payment/ProcessPaymentResultNotification";//支付结果通知地址
                    order.AttachData = "attachData";// 商户备注
                    //locationToken

                    DateTime dtNow = DateTime.Now;
                    order.TransactionStartTime = dtNow.ToString("yyyyMMddHHmmss");//开始时间
                    order.TransactionEndTime = dtNow.AddMinutes(30).ToString("yyyyMMddHHmmss");//结束时间

                    order.NonceStr = Config.GenerateRandomKey(32);//随机字符串
                    order.AreaInfo = store?.Address ?? merchant?.Address ?? "440100";// orderDto.AreaInfo;//地区信息六位数
                                                                                     //channelMchtNo

                    // 主要字段
                    sentent = "{\"version\":\"" + order.Version + "\",\"outTradeNo\":\"" + order.OutTradeNo + "\",\"customerCode\":\"" + order.CustomerCode + "\"," +
                        "\"appId\":\"" + order.SubAppId + "\",\"openId\":\"" + order.OpenId + "\",\"clientIp\":\"" + order.ClientIp + "\"," +
                        "\"orderInfo\":" + order.OrderInfo + "," +
                        "\"payAmount\":" + order.PayAmount + ",\"payCurrency\":\"" + order.PayCurrency + "\",\"payMethod\":\"" + order.PayMethod + "\"," +
                        "\"noCreditCards\":\"" + order.NoCreditCards + "\",\"notifyUrl\":\"" + order.NotifyUrl + "\"," +
                        "\"attachData\":\"" + order.AttachData + "\",\"transactionStartTime\":\"" + order.TransactionStartTime + "\"," +
                        "\"transactionEndTime\":\"" + order.TransactionEndTime + "\",\"areaInfo\":\"" + order.AreaInfo + "\",\"nonceStr\":\"" + order.NonceStr + "\"}";

                    // 可选字段（类似第1000行的模式）
                    //sentent += "\"locationToken\":\"\",\"channelMchtNo\":\"\",\"extUserInfo\":\"\",\"terminalInfo\":\"\",\"coupons\":\"\"}";

                }

                //支付宝内扫码支付
                if (dto.PayMethod == "99")
                {
                    string userId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                    var userMini = await _paymentIOC._sysUserMiniProgramEFCore.QueryAll(d => d.Id == userId).FirstOrDefaultAsync();
                    url = $"{apiBaseUrl}/api/txs/pay/AliJSAPIPayment";

                    order.Version = "3.0";//版本号
                    order.OutTradeNo = outTradeNo;//商户订单号
                    order.CustomerCode = "562294004495976";// 商户号
                    order.ClientIp = "118.196.30.7";//用户终端IP
                    order.BuyerId = userMini.UserId;//dto.BuyerId;//买家的支付宝唯一用户号
                    //order.BuyerLogonId = "0925NHeCm5ZP7AGmFk6QAGasdTDM92xFR7APB0fFhi7NrQf";

                    orderDto.OrderInfo.Id = outTradeNo;//商品订单编号
                    orderDto.OrderInfo.BusinessType = "100001"; // 业务类型
                    orderDto.OrderInfo.GoodsList.Add(new EpaylinksGoods { Amount = orderDto.PayAmount, Name = merchant?.Name, Number = "1" });//商品信息
                    order.OrderInfo = Config.SerializeToJson(orderDto.OrderInfo);

                    //order.payAmount
                    order.PayMethod = dto.PayMethod;//支付方式
                    order.PayCurrency = orderDto.PayCurrency;// 支持币种
                    order.NoCreditCards = "false";// 是否禁用信用卡（花呗不能用）
                    order.NotifyUrl = $"{_configuration["SelfUrl"]}/api/Payment/ProcessPaymentResultNotification";//支付结果通知地址
                    order.AttachData = "attachData";// 商户备注
                    //locationToken

                    DateTime dtNow = DateTime.Now;
                    order.TransactionStartTime = dtNow.ToString("yyyyMMddHHmmss");//开始时间
                    order.TransactionEndTime = dtNow.AddMinutes(30).ToString("yyyyMMddHHmmss");//结束时间

                    order.NonceStr = Config.GenerateRandomKey(32);//随机字符串
                    order.AreaInfo = store?.Address ?? merchant?.Address ?? "440100";// orderDto.AreaInfo;//地区信息六位数

                    sentent = "{\"version\":\"" + order.Version + "\",\"outTradeNo\":\"" + order.OutTradeNo + "\",\"customerCode\":\"" + order.CustomerCode + "\"," +
    "\"clientIp\":\"" + order.ClientIp + "\",\"buyerId\":\"" + order.BuyerId + "\"," +
    "\"orderInfo\":" + order.OrderInfo + "," +
    "\"payAmount\":" + order.PayAmount + ",\"paymentStatus\":" + order.PaymentStatus + ",\"payCurrency\":\"" + order.PayCurrency + "\"," +
    "\"noCreditCards\":\"" + order.NoCreditCards + "\",\"notifyUrl\":\"" + order.NotifyUrl + "\"," +
    "\"attachData\":\"" + order.AttachData + "\",\"transactionStartTime\":\"" + order.TransactionStartTime + "\"," +
    "\"transactionEndTime\":\"" + order.TransactionEndTime + "\",\"nonceStr\":\"" + order.NonceStr + "\",\"areaInfo\":\"" + order.AreaInfo + "\",\"buyerLogonId\":\"" + order.BuyerLogonId + "\"}";
                }

                await _paymentIOC._orderEFCore.AddAsync(order);
                //var orderResult = await _paymentIOC._orderEFCore.SaveChangesAsync();
                var orderResult = await _unitOfWork.SaveChangesAsync();

                if (orderResult == 0)
                {
                    return GetResult(message: "交易失败，请稍后重试！");
                }
                await _unitOfWork.CommitAsync();

                //调用易票联接口
                var result = await epaylinksService.post(sentent, url);
                var res = Config.DeserializeFromJson<EpaylinksResponseDto>(result);

                return GetResult(res.ReturnCode == "0000" ? 1 : 0, message: res.ReturnMsg, data: result);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 微信公众号/小程序支付
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> MiniProgramPaymentAsync(MiniProgramPaymentRequestDto dto)
        {
            try
            {
                string userId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                dto.CustomerCode = "562294004495976";
                //dto.AppId = "wxf996db986e976eb7";
                //dto.OpenId = "o0vZXxOTkb8os-c_v6HMm09RyNjw";

                var userMini = await _paymentIOC._sysUserMiniProgramEFCore.QueryAll(d => d.Id == userId).FirstOrDefaultAsync();
                if (userMini == null)
                {
                    return GetResult(0, "用户未登录");
                }
                dto.AppId = userMini.AppId;
                dto.OpenId = userMini.OpenId;

                var apiBaseUrl = _configuration["PaymentApi:BaseUrl"];
                string url = $"{apiBaseUrl}/api/txs/pay/WxJSAPICashier";
                string sentent = "{\"customerCode\":\"" + dto.CustomerCode +
        "\",\"outTradeNo\":\"" + dto.OutTradeNo +
        "\",\"appId\":\"" + dto.AppId +
        "\",\"openId\":\"" + dto.OpenId +
        "\",\"location\":\"" + dto.Location +
        "\",\"orderToken\":\"" + dto.OrderToken +
        "\"}";
                // 发送请求并处理响应
                var result = await epaylinksService.post(sentent, url);

                var res = Config.DeserializeFromJson<EpaylinksResponseDto>(result);
                return GetResult(res.ReturnCode == "0000" ? 1 : 0, message: res.ReturnMsg, data: result);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 支付结果回调
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<EpaylinksResponseDto> ProcessPaymentResultNotificationAsync(PaymentResultNotificationRequestDto dto)
        {
            try
            {

                if (string.IsNullOrEmpty(dto.CustomerCode) || string.IsNullOrEmpty(dto.OutTradeNo))
                {
                    return new EpaylinksResponseDto
                    {
                        ReturnCode = "0001",
                        ReturnMsg = "商户编号或订单号为空"
                    };
                }

                // 验证支付成功时必填字段
                if (dto.PayState == "00") // 假设 00 表示支付成功
                {
                    if (string.IsNullOrEmpty(dto.TransactionNo) || !dto.ProcedureFee.HasValue)
                    {
                        return new EpaylinksResponseDto
                        {
                            ReturnCode = "0001",
                            ReturnMsg = "支付成功时，易票联订单号和手续费为必填项"
                        };
                    }
                }

                var order = await _paymentIOC._orderEFCore.QueryAll(d => d.CustomerCode == dto.CustomerCode && d.OutTradeNo == dto.OutTradeNo).FirstOrDefaultAsync();
                if (order != null)
                {
                    order.TransactionNo = dto.TransactionNo;
                    order.ChannelOrder = dto.ChannelOrder;
                    order.TerminalNo = dto.TerminalNo;
                    order.TerminalName = dto.TerminalName;
                    order.PaymentStatus = Config.PaymentStatusTransition(dto.PayState);
                    order.PaymentTime = Config.ParseTimeString(dto.PayTime);
                    order.ProcedureFee = dto.ProcedureFee;
                    order.CashAmount = dto.CashAmount;
                    order.CouponAmount = dto.CouponAmount;
                    order.PayServiceCharged = dto.PayServiceCharged;
                    if (dto.IpInfo != null)
                        order.IpInfo = Config.SerializeToJson(dto.IpInfo);
                    order.IpProtocolVersion = dto.IpProtocolVersion;
                    order.IrrType = dto.IrrType;
                    order.Irr = dto.Irr;
                    order.NfcTagId = dto.NfcTagId;
                    order.OpenId = dto.OpenId;
                    order.SubOpenId = dto.SubOpenId;
                    order.BuyerId = dto.BuyerId;
                    order.BuyerLogonId = dto.BuyerLogonId;
                    order.Remark = dto.Remark;
                    order.Reserved = dto.Reserved;
                    if (dto.CouponDetails != null)
                        order.CouponDetails = Config.SerializeToJson(dto.CouponDetails);

                    var merchant = await _paymentIOC._merchantEFCore.QueryAll(d => d.Id == order.MerchantId).FirstOrDefaultAsync();
                    if (string.IsNullOrEmpty(order.DividedAgreementId))
                    {
                        //支付成功转入待结算余额
                        await AddAccountTransactionAsync(new AccountTransactionRequestDto
                        {
                            UserId = merchant.CreatorId,
                            Amount = order.SettlementAmount,
                            OrderId = order.Id,
                            TransactionType = 7,//商户订单直接营收
                            BalanceType = 4, //待结算
                        });
                    }
                    else
                    {
                        //支付成功转入待分账余额
                        await AddAccountTransactionAsync(new AccountTransactionRequestDto
                        {
                            UserId = merchant.CreatorId,
                            Amount = order.SettlementAmount,
                            OrderId = order.Id,
                            TransactionType = 1,
                            BalanceType = 5, //待分账
                        });
                    }

                    await _paymentIOC._orderEFCore.UpdateAsync(order);
                    var result = await _paymentIOC._orderEFCore.SaveChangesAsync();

                    // 在订单状态落库后，根据支付结果处理优惠券核销的确认/撤销（幂等）
                    if (!string.IsNullOrEmpty(order.CouponInstanceId))
                    {
                        try
                        {
                            if (dto.PayState == "00")
                            {
                                // 回调成功 -> 确认核销
                                await _couponService.ConfirmCouponConsumptionAsync(order.CouponInstanceId, order.Id);
                            }
                            else
                            {
                                // 非成功状态 -> 撤销占用
                                await _couponService.CancelCouponConsumptionAsync(order.CouponInstanceId, order.Id);
                            }
                        }
                        catch (Exception ex)
                        {
                            // 记录日志，不影响对第三方的响应
                            Console.WriteLine($"处理优惠券核销确认/撤销时发生异常: {ex.Message}");
                        }
                    }

                    if (result >= 1)
                        return new EpaylinksResponseDto
                        {
                            ReturnCode = "0000",
                            ReturnMsg = "处理成功"
                        };
                    else
                        return new EpaylinksResponseDto
                        {
                            ReturnCode = "0001",
                            ReturnMsg = $"处理异常订单: {dto.OutTradeNo}"
                        };
                }
                else
                {
                    return new EpaylinksResponseDto
                    {
                        ReturnCode = "0001",
                        ReturnMsg = $"商户侧未找到订单: {dto.OutTradeNo}"
                    };
                }
            }
            catch (Exception ex)
            {
                // 记录异常日志
                Console.WriteLine($"处理支付结果通知时发生异常: {ex.Message}");
                return new EpaylinksResponseDto
                {
                    ReturnCode = "0001",
                    ReturnMsg = $"处理异常: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 支付结果查询
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> QueryPaymentResultAsync(PaymentQueryRequestDto dto)
        {
            try
            {
                // 这里实现具体的查询业务逻辑，例如根据商户编号和订单号去查询支付结果
                // 示例：简单验证参数
                if (string.IsNullOrEmpty(dto.CustomerCode) || string.IsNullOrEmpty(dto.NonceStr))
                {

                    return GetResult(0, message: "商户编号或随机字符串为空", data: new { dto.NonceStr });
                }

                if (string.IsNullOrEmpty(dto.OutTradeNo) && string.IsNullOrEmpty(dto.TransactionNo))
                {
                    return GetResult(0, message: "商户订单号和易票联订单号不能同时为空", data: new { dto.NonceStr });
                }

                var apiBaseUrl = _configuration["PaymentApi:BaseUrl"];
                var url = $"{apiBaseUrl}/api/txs/pay/PaymentQuery";

                var result = await epaylinksService.post(Config.SerializeToJson(dto), url);
                var data = Config.DeserializeFromJson<PaymentQueryResponseDto>(result);

                var res = Config.DeserializeFromJson<EpaylinksResponseDto>(result);

                return GetResult(res.ReturnCode == "0000" ? 1 : 0, message: res.ReturnMsg, data: data);
            }
            catch (Exception ex)
            {
                // 记录异常日志
                Console.WriteLine($"查询支付结果时发生异常: {ex.Message}");
                return GetResult(0, message: $"查询异常: {ex.Message}", data: new { dto.NonceStr });
            }
        }

        /// <summary>
        /// 主动查询并更新付款状态
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult> ManualQueryAndUpdateOrder(PaymentQueryRequestDto request)
        {

            var order = await _paymentIOC._orderEFCore.QueryAll(d => d.CustomerCode == request.CustomerCode && d.OutTradeNo == request.OutTradeNo).FirstOrDefaultAsync();
            if (order != null)
            {
                var res = await QueryPaymentResultAsync(request);

                if (res.code == ApiCode.fail)
                    return GetResult(0, $"主动查询订单: {request.OutTradeNo}失败");

                var dto = res.data as PaymentQueryResponseDto;
                if (order.PaymentStatus == 0)
                {

                    order.TransactionNo = dto.TransactionNo;
                    order.ChannelOrder = dto.ChannelOrder;
                    order.TerminalNo = dto.TerminalNo;
                    order.TerminalName = dto.TerminalName;
                    order.PaymentStatus = Config.PaymentStatusTransition(dto.PayState);
                    order.PaymentTime = Config.ParseTimeString(dto.PayTime);
                    order.ProcedureFee = dto.ProcedureFee;
                    order.CashAmount = dto.CashAmount;
                    order.CouponAmount = dto.CouponAmount;
                    order.PayServiceCharged = dto.PayServiceCharged;
                    if (dto.IpInfo != null)
                        order.IpInfo = Config.SerializeToJson(dto.IpInfo);
                    order.IpProtocolVersion = dto.IpProtocolVersion;
                    order.IrrType = dto.IrrType;
                    order.Irr = dto.Irr;
                    order.NfcTagId = dto.NfcTagId;
                    order.OpenId = dto.OpenId;
                    order.SubOpenId = dto.SubOpenId;
                    order.BuyerId = dto.BuyerId;
                    order.BuyerLogonId = dto.BuyerLogonId;
                    order.Remark = dto.Remark;
                    order.Reserved = dto.Reserved;
                    if (dto.CouponDetails != null)
                        order.CouponDetails = Config.SerializeToJson(dto.CouponDetails);
                }
                else
                {
                    order.Remark = dto.ReturnMsg;
                }

                await _paymentIOC._orderEFCore.UpdateAsync(order);
                var result = await _paymentIOC._orderEFCore.SaveChangesAsync();

                return GetResult(result);
            }
            else
            {
                return GetResult(0, $"商户侧未找到订单: {request.OutTradeNo}");
            }

        }

        /// <summary>
        /// 获取交易订单列表（ToB）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetOrdersListToBAsync(OrderQueryRequestDto dto)
        {
            var permission = await _userService.GetCurUserRolePermissionAsync();
            List<string> storeIds = new List<string>();
            List<string> codeIds = new List<string>();
            if (permission != null)
            {
                if (permission.RoleType == 5)//店长
                {
                    storeIds = permission.StoreIds;
                    if (storeIds.Count() < 1)
                        return GetResult(1, "无关联数据");
                }
                else if (permission.RoleType == 6)//收银员
                {
                    codeIds = permission.CodeIds;
                    if (codeIds.Count() < 1)
                        return GetResult(1, "无关联数据");
                }

                if (storeIds.Count == 0 && !string.IsNullOrEmpty(dto.StoreId))
                    storeIds.Add(dto.StoreId);
                if (codeIds.Count == 0 && !string.IsNullOrEmpty(dto.CodeId))
                    codeIds.Add(dto.CodeId);
            }

            var data = await _paymentIOC._orderEFCore.QueryAll(out int total, dto.Page, dto.Limit,
                d => (string.IsNullOrEmpty(dto.Key) || d.OrderCode.Contains(dto.Key))
                && (string.IsNullOrEmpty(dto.MerchantId) || d.MerchantId == dto.MerchantId)
                && (!storeIds.Any() || storeIds.Contains(d.StoreId))
                && (!codeIds.Any() || codeIds.Contains(d.CodeId))
                && d.PaymentStatus == dto.PaymentStatus
                && (dto.IsDividedAgreement == null || (dto.IsDividedAgreement == false && string.IsNullOrEmpty(d.DividedAgreementId)) || (dto.IsDividedAgreement == true && !string.IsNullOrEmpty(d.DividedAgreementId)))
                && ((dto.BeginTime == null || dto.EndTime == null) || (dto.BeginTime <= d.CreationTime && dto.EndTime >= d.CreationTime)
                 ),
                d => d.CreationTime, false).Select(d => new OrderQueryResponseDto
                {
                    Id = d.Id,
                    OrderCode = d.OrderCode,
                    OrderType = d.OrderType,
                    PayMethod = d.PayMethod,
                    OrderAmount = d.OrderAmount,
                    PayAmount = (long)d.PayAmount,
                    CouponInstanceId = d.CouponInstanceId,
                    DiscountAmount = d.DiscountAmount,
                    CreationTime = d.CreationTime,
                    PaymentTime = d.PaymentTime,
                    PaymentStatus = d.PaymentStatus,
                    OrderSnapshot = d.OrderSnapshot,
                    TotalRefundAmount = d.TotalRefundAmount,
                }).ToListAsync();

            data.ForEach(d =>
            {

                try
                {
                    var orderSnapshot = Config.DeserializeFromJson<OrderSnapshotModel>(d.OrderSnapshot);
                    if (orderSnapshot != null)
                    {
                        d.StoreName = orderSnapshot.StoreName;
                        d.CodeName = orderSnapshot.CodeName;
                        d.OrderSnapshot = "{}";
                    }
                }
                catch (JsonException ex)
                {
                    // 处理反序列化异常
                }
            });

            return GetResult(1, data: new
            {
                total,
                data
            });
        }

        /// <summary>
        /// 获取交易订单列表（ToC）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetOrdersListToCAsync(OrderQueryRequestDto dto)
        {
            string userId = _httpContextAccessor.HttpContext?.GetCurrentUserId() ?? string.Empty;
            if (string.IsNullOrEmpty(userId))
            {
                return GetResult(message: "用户未登录或未提供有效的用户ID，请稍后重试！");
            }

            var data = await _paymentIOC._orderEFCore.QueryAll(out int total, dto.Page, dto.Limit,
                d => userId.Contains(d.UserId),
                d => d.CreationTime, false).Select(d => new OrderQueryResponseDto
                {
                    Id = d.Id,
                    OrderCode = d.OrderCode,
                    OrderType = d.OrderType,
                    PayMethod = d.PayMethod,
                    OrderAmount = d.OrderAmount,
                    PayAmount = (long)d.PayAmount,
                    CouponInstanceId = d.CouponInstanceId,
                    DiscountAmount = d.DiscountAmount,
                    CreationTime = d.CreationTime,
                    PaymentTime = d.PaymentTime,
                    OrderSnapshot = d.OrderSnapshot,
                    PaymentStatus = d.PaymentStatus,
                    TotalRefundAmount = d.TotalRefundAmount,
                }).ToListAsync();


            data.ForEach(d =>
            {

                try
                {
                    var orderSnapshot = Config.DeserializeFromJson<OrderSnapshotModel>(d.OrderSnapshot);
                    if (orderSnapshot != null)
                    {
                        d.StoreName = orderSnapshot.StoreName;
                        d.OrderSnapshot = "{}";
                    }
                }
                catch (JsonException ex)
                {
                    // 处理反序列化异常
                }
            });

            return GetResult(1, data: new
            {
                total,
                data
            });
        }

        /// <summary>
        /// 获取消费统计数据（C端用户）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetConsumptionStatistics()
        {
            string userId = _httpContextAccessor.HttpContext?.GetCurrentUserId() ?? string.Empty;
            if (string.IsNullOrEmpty(userId))
            {
                return GetResult(message: "用户未登录或未提供有效的用户ID，请稍后重试！");
            }
            var data = await _paymentIOC._orderEFCore.QueryAll(d => userId.Contains(d.UserId)).Select(d => new OrderQueryResponseDto
            {
                Id = d.Id,
                OrderCode = d.OrderCode,
                OrderType = d.OrderType,
                PayMethod = d.PayMethod,
                OrderAmount = d.OrderAmount,
                PayAmount = (long)d.PayAmount,
                DiscountAmount = (long)d.DiscountAmount,
            }).ToListAsync();

            int total = data.Count;
            long totalDiscountAmount = (long)data.Sum(d => d.DiscountAmount);
            long totalConsumption = (long)data.Sum(d => d.PayAmount);

            return GetResult(1, data: new
            {
                total,
                totalDiscountAmount,
                totalConsumption
            });
        }

        /// <summary>
        /// 获取单个交易订单详细信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetOrdersAsync(OrderQueryRequestDto dto)
        {
            var data = await _paymentIOC._orderEFCore.QueryAll(d => (string.IsNullOrEmpty(dto.Id) || d.Id.Contains(dto.Id))
            && (string.IsNullOrEmpty(dto.TransactionNo) || d.TransactionNo.Contains(dto.TransactionNo))).Select(d => new OrderResponseDto
            {
                Id = d.Id,
                OrderCode = d.OrderCode,
                OrderType = d.OrderType,
                PayMethod = d.PayMethod,

                OrderAmount = d.OrderAmount,
                CouponInstanceId = d.CouponInstanceId,
                DiscountAmount = (long)d.DiscountAmount,
                PayAmount = (long)d.PayAmount,
                SettlementAmount = (long)d.SettlementAmount,

                PlatformServiceFeeRate = d.PlatformServiceFeeRate,
                PlatformServiceFee = (long)d.PlatformServiceFee,

                Rate = d.Rate,
                Commission = d.Commission,

                CodeId = d.CodeId,
                StoreId = d.StoreId,
                MerchantId = d.MerchantId,

                OpenId = d.OpenId,
                SubAppId = d.SubAppId,
                UserId = d.UserId,
                DeviceId = d.DeviceId,

                OrderSnapshot = d.OrderSnapshot,
                CreationTime = d.CreationTime,

                OutTradeNo = d.OutTradeNo,
                ChannelOrder = d.ChannelOrder,
                TransactionNo = d.TransactionNo,
                PaymentTime = d.PaymentTime,
                PaymentStatus = d.PaymentStatus,

                RefundStatus = d.RefundStatus,
                //RefundTime = d.RefundTime,
                TotalRefundAmount = d.TotalRefundAmount,
                RefundCount = d.RefundCount,
                LastRefundTime = d.LastRefundTime,

                RecommendMerchantId = d.RecommendMerchantId,
                RecommendationCommissionAmount = (long)d.RecommendationCommissionAmount,

                IsSettlement = d.IsSettlement,
                SettlementDate = d.SettlementDate,
                SettlementTime = d.SettlementTime,

                DividedAgreementId = d.DividedAgreementId,
                IsDivided = d.IsDivided,
                DividedDate = d.DividedDate,
                DividedTime = d.DividedTime,

                RefundableAmount = d.RefundableAmount,
                RefundProcessStatus = d.RefundProcessStatus
            }).FirstOrDefaultAsync();

            try
            {
                var orderSnapshot = Config.DeserializeFromJson<OrderSnapshotModel>(data.OrderSnapshot);
                if (orderSnapshot != null)
                {
                    data.Code = orderSnapshot.Code;
                    data.CodeName = orderSnapshot.CodeName;
                    data.StoreCode = orderSnapshot.StoreCode;
                    data.StoreName = orderSnapshot.StoreName;
                    data.MerchantCode = orderSnapshot.MerchantCode;
                    data.MerchantName = orderSnapshot.MerchantName;
                    data.AgreementCode = orderSnapshot.AgreementCode;
                    data.AgreementName = orderSnapshot.AgreementName;
                    data.DividedCycle = orderSnapshot.DividedCycle;
                    data.SettlementCycle = orderSnapshot.SettlementCycle;
                    data.AgreementDetails = orderSnapshot.AgreementDetails;
                    data.SnapshotTime = orderSnapshot.SnapshotTime;
                }
            }
            catch (JsonException ex)
            {
                // 处理反序列化异常
            }

            data.orderRefundRecords = await _paymentIOC._orderRefundRecordEFCore.QueryAll(d => d.OrderId == data.Id).Select(d => new OrderRefundRecordResponseDto
            {
                Id = d.Id,
                OrderId = d.OrderId,
                CustomerCode = d.CustomerCode,
                OutRefundNo = d.OutRefundNo,
                OutTradeNo = d.OutTradeNo,
                TransactionNo = d.TransactionNo,
                RefundAmount = d.RefundAmount,
                OriginalAmount = d.OriginalAmount,
                Remark = d.Remark,
                ProcedureFee = d.ProcedureFee,
                RefundTime = d.RefundTime,
                ChannelTradeNo = d.ChannelTradeNo,
                Status = d.Status,
                IsAutoRefund = d.IsAutoRefund,
                CreationTime = d.CreationTime,
                LastModificationTime = d.LastModificationTime,
                ExtraProperties = d.ExtraProperties,
            }).ToListAsync();

            return GetResult(1, data: data);
        }

        /// <summary>
        /// 新增结算记录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddSettlementRecordAsync(DateTime? settlementTime)
        {
            try
            {
                DateTime currentTime = (DateTime)(settlementTime == null ? DateTime.Now : settlementTime);
                DateTime dateOnly = currentTime.Date; // 只取日期部分（时间为 00:00:00）

                //查找结算日期对应的订单并且没有结算过的订单
                var orders = await _paymentIOC._orderEFCore.QueryAll(d => d.SettlementDate == dateOnly && d.IsSettlement == 0 && d.PaymentStatus == 1).ToListAsync();

                var merchants = await _paymentIOC._merchantEFCore.QueryAll(null).Select(d => new { d.Id, d.Name, d.CreatorId }).ToListAsync();
                //遍历每个商户，单独处理结算记录
                foreach (var merchant in merchants)
                {
                    await _unitOfWork.BeginTransactionAsync(System.Data.IsolationLevel.ReadCommitted);

                    try
                    {
                        // 筛选当前商户的分账记录
                        var merchantOrders = orders.Where(e => e.MerchantId == merchant.Id).ToList();

                        if (merchantOrders.Count == 0)
                        {
                            // 如果当前商户没有订单，则跳过该商户结算
                            await _unitOfWork.DisposeAsync();
                            continue;
                        }

                        // 创建当前商户的结算记录
                        string settlementRecordId = Config.GUID();
                        SettlementRecord settlementRecord = new SettlementRecord()
                        {
                            Id = settlementRecordId,
                            SettlementNo = Config.GenerateCode("SET"),
                            SettlementDate = dateOnly,
                            SettlementType = settlementTime == null ? 0 : 1,
                            MerchantId = merchant.Id,
                            Status = 1,
                            CreationTime = DateTime.Now,
                        };

                        // 计算结算总金额
                        settlementRecord.TotalActualReceivedAmount = (long)merchantOrders.Sum(d => d.PayAmount);// 总实收金额
                        settlementRecord.TotalRefundAmount = (long)merchantOrders.Sum(d => d.TotalRefundAmount);// 总退款金额
                        settlementRecord.RefundCount = merchantOrders.Count(d => d.RefundStatus == 1);// 退款订单数量
                        settlementRecord.TotalDiscountAmount = merchantOrders.Sum(d => d.DiscountAmount);// 总优惠金额
                        settlementRecord.DiscountCount = merchantOrders.Count(d => !string.IsNullOrEmpty(d.CouponInstanceId));// 使用优惠券订单数量
                        settlementRecord.TotalSettledAmount = (long)merchantOrders.Sum(d => d.SettlementAmount);// 总结算金额
                        settlementRecord.SettlementCount = merchantOrders.Count();// 结算订单数量
                        settlementRecord.Commission = (long)merchantOrders.Sum(d => d.Commission);// 总手续费
                        settlementRecord.PlatformServiceFee = (long)merchantOrders.Sum(d => d.PlatformServiceFee);// 平台服务费

                        //将当前商户订单批量结算标记
                        foreach (var merchantOrder in merchantOrders)
                        {
                            merchantOrder.IsSettlement = 1; // 标记为已结算
                            merchantOrder.SettlementTime = DateTime.Now;
                            merchantOrder.LastModificationTime = DateTime.Now;

                            //没有分账协议的订单直接将结算金额到商户主账户交易记录入账
                            if (string.IsNullOrEmpty(merchantOrder.DividedAgreementId))
                            {
                                //先从待结算余额扣除
                                await AddAccountTransactionAsync(new AccountTransactionRequestDto
                                {
                                    UserId = merchant.CreatorId,
                                    Amount = -merchantOrder.SettlementAmount,
                                    OrderId = merchantOrder.Id,
                                    TransactionType = 4,//结算转入可提现余额
                                    BalanceType = 4
                                }, false);
                                //再增加到可提现余额
                                await AddAccountTransactionAsync(new AccountTransactionRequestDto
                                {
                                    UserId = merchant.CreatorId,
                                    Amount = merchantOrder.SettlementAmount,
                                    OrderId = merchantOrder.Id,
                                    TransactionType = 4,
                                    BalanceType = 3
                                }, false);
                            }

                            //商户优惠券互推佣金入账
                            if (!string.IsNullOrEmpty(merchantOrder.RecommendMerchantId))
                            {
                                var recommendMerchant = await _paymentIOC._merchantEFCore.QueryAll(d => d.Id == merchantOrder.RecommendMerchantId).FirstOrDefaultAsync();
                                if (recommendMerchant != null)
                                {
                                    await AddAccountTransactionAsync(new AccountTransactionRequestDto
                                    {
                                        UserId = recommendMerchant.CreatorId,
                                        Amount = merchantOrder.RecommendationCommissionAmount,
                                        OrderId = merchantOrder.Id,
                                        TransactionType = 6,//优惠券互推收入
                                        BalanceType = 3
                                    }, false);
                                }
                            }
                        }

                        // 保存结算记录
                        await _paymentIOC._settlementRecordEFCore.AddAsync(settlementRecord);
                        var affectedRecord = await _unitOfWork.SaveChangesAsync();
                        if (affectedRecord < 1)
                            throw new Exception($"{merchant.Name}：{merchant.Id}商户结算记录保存失败!");

                        // 批量更新订单结算状态
                        await _paymentIOC._orderEFCore.UpdateRangeAsync(merchantOrders);
                        var affectedorder = await _unitOfWork.SaveChangesAsync();
                        if (affectedorder < merchantOrders.Count)
                        {
                            throw new Exception($"{merchant.Name}：{merchant.Id}商户单结算状态更新不完整，受影响行数不符!");
                        }

                        // 提交当前商户的事务
                        await _unitOfWork.CommitAsync();

                    }
                    catch (Exception ex)
                    {
                        await _unitOfWork.RollbackAsync();
                        // 记录当前商户的错误
                        await _logService.AddErrorLogAsync(new ErrorLogRequestDto
                        {
                            Api = "AddSettlementRecordAsync",
                            Message = $"定时新增结算任务执行失败: {ex}",
                            Params = $"",
                            UserId = ""
                        });
                        //重试机制
                        // 继续处理下一个商户
                        continue;
                    }
                    finally
                    {
                    }
                }

                //已结算的订单，平台手续费和优惠券服务费入账
                var settlementOrders = await _paymentIOC._orderEFCore
                    .QueryAll(d => d.SettlementDate == dateOnly && d.IsSettlement == 1 && d.PaymentStatus == 1)
                    .AsNoTracking()
                    .GroupBy(_ => 1)
                    .Select(d => new
                    {
                        Commission = (long)d.Sum(x => x.Commission) - (long)d.Sum(x => x.ProcedureFee),
                        PlatformServiceFee = (long)d.Sum(x => x.PlatformServiceFee) - (long)d.Sum(x => x.RecommendationCommissionAmount),
                    })
                    .FirstOrDefaultAsync() ?? new
                    {
                        Commission = 0L,
                        PlatformServiceFee = 0L,
                    };

                await AddPaymentPlatformTransactionAsync(new AccountTransactionRequestDto
                {
                    PaymentPlatformId = _configuration["PaymentPlatform:PlatformId"],
                    Amount = settlementOrders.Commission,
                    TransactionType = 10,//订单手续费
                    BalanceType = 1
                });

                await AddPaymentPlatformTransactionAsync(new AccountTransactionRequestDto
                {
                    PaymentPlatformId = _configuration["PaymentPlatform:PlatformId"],
                    Amount = settlementOrders.PlatformServiceFee,
                    TransactionType = 12,//优惠券服务费
                    BalanceType = 1
                });

                return GetResult(1); // 所有商户处理完成（无论单个失败与否，整体返回成功）
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取结算记录列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetSettlementRecordListAsync(SettlementRecordQueryRequestDto dto)
        {
            var data = await _paymentIOC._settlementRecordEFCore.QueryAll(d =>
                (string.IsNullOrEmpty(dto.MerchantId) || d.MerchantId.Contains(dto.MerchantId))
                && (d.SettlementDate >= dto.BeginTime.Date && d.SettlementDate <= dto.EndTime.Date),
                d => d.CreationTime, false).ToListAsync();
            return GetResult(1, data: data);
        }

        /// <summary>
        /// 新增账户交易记录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddAccountTransactionAsync(AccountTransactionRequestDto dto, bool useTransaction = true)
        {
            try
            {
                TransactionScope? scope = null;
                if (useTransaction)
                {
                    var txOptions = new System.Transactions.TransactionOptions
                    {
                        IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted,//当前事务锁定记录，防止脏读
                        Timeout = TimeSpan.FromMinutes(2)
                    };
                    scope = new TransactionScope(TransactionScopeOption.Required, txOptions, TransactionScopeAsyncFlowOption.Enabled);
                }

                try
                {
                    // 先查询获取ID
                    var accountId = await _paymentIOC._sysUserEFCore.QueryAll(d => d.Id == dto.UserId)
                        .Select(x => x.Id)
                        .FirstOrDefaultAsync();

                    if (accountId == null)
                        return GetResult(message: "查询当前用户失败，请稍后重试！");

                    // 构造交易记录（余额在原子更新后查询最新值再回填）
                    var accountTransaction = new AccountTransaction()
                    {
                        Id = Config.GUID(),
                        TransactionNo = Config.GUID(),
                        UserId = dto.UserId,
                        Amount = (long)dto.Amount,
                        TransactionType = (int)dto.TransactionType,
                        TransactionTime = DateTime.Now,
                        Remark = dto.Remark,
                        BalanceType = dto.BalanceType,
                        DividedRecordDetailId = dto.DividedRecordDetailId,
                        OrderId = dto.OrderId,
                        WithdrawalRecordId = dto.WithdrawalRecordId,
                    };

                    // 原子更新余额，避免并发下读-改-写冲突；随后读取最新余额
                    int userUpdateAffected = 0;
                    long? newBalance = null;

                    if (dto.BalanceType == 3) // 可提现余额
                    {
                        userUpdateAffected = await _paymentIOC._sysUserEFCore
                            .QueryAll(u => u.Id == accountId)
                            .ExecuteUpdateAsync(setters => setters
                                .SetProperty(u => u.WithdrawableBalance, u => u.WithdrawableBalance + accountTransaction.Amount));

                        newBalance = await _paymentIOC._sysUserEFCore
                            .QueryAll(u => u.Id == accountId)
                            .Select(u => (long?)u.WithdrawableBalance)
                            .SingleAsync();
                    }
                    if (dto.BalanceType == 4) // 未结算余额
                    {
                        userUpdateAffected = await _paymentIOC._sysUserEFCore
                            .QueryAll(u => u.Id == accountId)
                            .ExecuteUpdateAsync(setters => setters
                                .SetProperty(u => u.UnsettledBalance, u => u.UnsettledBalance + accountTransaction.Amount));

                        newBalance = await _paymentIOC._sysUserEFCore
                            .QueryAll(u => u.Id == accountId)
                            .Select(u => (long?)u.UnsettledBalance)
                            .SingleAsync();
                    }
                    if (dto.BalanceType == 5) // 待分账余额
                    {
                        userUpdateAffected = await _paymentIOC._sysUserEFCore
                            .QueryAll(u => u.Id == accountId)
                            .ExecuteUpdateAsync(setters => setters
                                .SetProperty(u => u.DividedBalance, u => u.DividedBalance + accountTransaction.Amount));

                        newBalance = await _paymentIOC._sysUserEFCore
                            .QueryAll(u => u.Id == accountId)
                            .Select(u => (long?)u.DividedBalance)
                            .SingleAsync();
                    }

                    accountTransaction.BalanceAfter = newBalance ?? 0;

                    // 写入交易流水
                    await _paymentIOC._accountTransactionEFCore.AddAsync(accountTransaction);
                    int accountTransactionResult = await _paymentIOC._accountTransactionEFCore.SaveChangesAsync();


                    if (userUpdateAffected == 0 || accountTransactionResult == 0)
                    {
                        return GetResult(message: "系统繁忙交易入账失败，请稍后重试！");
                    }

                    if (useTransaction)
                        scope!.Complete();

                    return GetResult(1, data: accountTransaction.Id);
                }
                finally
                {
                    scope?.Dispose();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 新增支付平台交易记录
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="useTransaction"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddPaymentPlatformTransactionAsync(AccountTransactionRequestDto dto, bool useTransaction = true)
        {
            try
            {
                TransactionScope? scope = null;
                if (useTransaction)
                {
                    var txOptions = new System.Transactions.TransactionOptions
                    {
                        IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted,//当前事务锁定记录，防止脏读
                        Timeout = TimeSpan.FromMinutes(2)
                    };
                    scope = new TransactionScope(TransactionScopeOption.Required, txOptions, TransactionScopeAsyncFlowOption.Enabled);
                }

                try
                {
                    var paymentPlatformId = await _paymentIOC._paymentPlatformEFCore.QueryAll(d => d.Id == dto.PaymentPlatformId)
                        .Select(x => x.Id)
                        .FirstOrDefaultAsync();

                    if (paymentPlatformId == null)
                        return GetResult(message: "查询当前支付平台失败，请稍后重试！");


                    var accountTransaction = new AccountTransaction()
                    {
                        Id = Config.GUID(),
                        TransactionNo = Config.GUID(),
                        UserId = dto.UserId,
                        Amount = (long)dto.Amount,
                        TransactionType = (int)dto.TransactionType,
                        TransactionTime = DateTime.Now,
                        Remark = dto.Remark,
                        BalanceType = dto.BalanceType,
                        DividedRecordDetailId = dto.DividedRecordDetailId,
                        OrderId = dto.OrderId,
                        WithdrawalRecordId = dto.WithdrawalRecordId,
                        PaymentPlatformId = dto.PaymentPlatformId,
                    };


                    // 原子更新余额，避免并发下读-改-写冲突；随后读取最新余额
                    int platformUpdateAffected = 0;
                    long? newBalance = null;

                    if (dto.BalanceType == 1)
                    {
                        platformUpdateAffected = await _paymentIOC._paymentPlatformEFCore
                            .QueryAll(u => u.Id == paymentPlatformId)
                            .ExecuteUpdateAsync(setters => setters
                                .SetProperty(u => u.VirtualBalance, u => u.VirtualBalance + accountTransaction.Amount));
                        newBalance = await _paymentIOC._paymentPlatformEFCore
                            .QueryAll(u => u.Id == paymentPlatformId)
                            .Select(u => (long?)u.VirtualBalance)
                            .SingleAsync();
                    }

                    accountTransaction.BalanceAfter = newBalance ?? 0;

                    // 写入交易流水
                    await _paymentIOC._accountTransactionEFCore.AddAsync(accountTransaction);
                    int accountTransactionResult = await _paymentIOC._accountTransactionEFCore.SaveChangesAsync();

                    if (platformUpdateAffected == 0 || accountTransactionResult == 0)
                    {
                        return GetResult(message: "系统繁忙交易入账失败，请稍后重试！");
                    }

                    if (useTransaction)
                        scope!.Complete();

                    return GetResult(1, data: accountTransaction.Id);
                }
                finally
                {
                    scope?.Dispose();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        
        /// <summary>
        /// 新增支付平台
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddPaymentPlatformAsync(PaymentPlatformCreateRequestDto dto)
        {
            PaymentPlatform paymentPlatform = new PaymentPlatform()
            {
                Id = Config.GUID(),
                Name = dto.Name,
                Code = Config.GenerateCode(),
                Description = dto.Description,
                AcceptOrder = true,
                CreationTime = DateTime.Now,
                AcqSpId = dto.AcqSpId,
                AppId = dto.AppId,
                CallbackUrl = dto.CallbackUrl,
                SecretKey = dto.SecretKey,
                ExtraProperties = dto.ExtraProperties,
                EnableStatus = 1,
                ActivationStatus = 1,
                MerchantType = 0,
                WithdrawalMethod = 0,
                ConcurrencyStamp = Config.GUID(),
            };

            await _paymentIOC._paymentPlatformEFCore.AddAsync(paymentPlatform);
            var result = await _paymentIOC._paymentPlatformEFCore.SaveChangesAsync();

            return GetResult(result);
        }

        /// <summary>
        /// 获取支付平台列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetPaymentPlatformListAsync(PaymentPlatformQueryRequestDto dto)
        {
            var data = await _paymentIOC._paymentPlatformEFCore.QueryAll(out int total, dto.Page, dto.Limit,
                 d => (string.IsNullOrEmpty(dto.Key) || d.Name.Contains(dto.Key)),
                d => d.CreationTime, false).ToListAsync();

            return GetResult(1, data: new
            {
                total,
                data
            });
        }

        /// <summary>
        /// 费率计算
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> CalculateRateAsync(SplitWithdrawalRequestDto dto)
        {
            // 根据提现金额设置不同的费率
            var feeRate = dto.Amount >= 500000 ? 0.0005m : 0.001m; // 5000元及以上使用0.0005费率，否则使用0.001费率
            var fee = (long)((dto.Amount * feeRate) < 20 ? 20 : dto.Amount * feeRate);//单位为分，最低20分钱
            var sendAmount = dto.Amount - fee;//实际提现金额

            return GetResult(1, data: new SplitWithdrawalResponseDto
            {
                Amount = dto.Amount,
                Fee = fee,
                FeeRate = feeRate,
                SendAmount = sendAmount
            });
        }

        /// <summary>
        /// 分账并提现
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> SplitWithdrawalAsync(SplitWithdrawalRequestDto dto)
        {
            var AllowPayment = _configuration["PaymentPlatform:AllowPayment"];

            if (AllowPayment == "false")
            {
                return GetResult(0, message: "当前系统维护中，暂停业务，请稍后重试！");
            }

            var currentTime = DateTime.Now;
            var currentHour = currentTime.Hour;

            if (currentHour < 12 || currentHour >= 23)
            {
                return GetResult(0, message: "当前未到提现业务开发时间，请每天中午12点到晚上11点之内重试！");
            }

            EpaylinksSplitRecord splitRecord = new EpaylinksSplitRecord();
            try
            {
                //using var scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(2), TransactionScopeAsyncFlowOption.Enabled);

                var merchant = await _paymentIOC._merchantEFCore.QueryAll(d => d.Id == dto.MerId).FirstOrDefaultAsync();
                var paymentPlatform = await _paymentIOC._paymentPlatformEFCore.QueryAll(d => d.AcqSpId == merchant.AcqSpId).FirstOrDefaultAsync();

                var user = await _paymentIOC._sysUserEFCore.QueryAll(d => d.Id == merchant.CreatorId).FirstOrDefaultAsync();

                if (user == null)
                    return GetResult(message: "找不到当前账户，请稍后重试！");

                // 检查余额是否足够提现金额
                if (user.WithdrawableBalance < dto.Amount)
                    return GetResult(message: "可提现余额不足！");


                // 根据提现金额设置不同的费率
                var feeRate = dto.Amount >= 500000 ? 0.0005m : 0.001m; // 5000元及以上使用0.0005费率，否则使用0.001费率
                var fee = (long)((dto.Amount * feeRate) < 20 ? 20 : dto.Amount * feeRate);//单位为分，最低20分钱

                var sendAmount = dto.Amount - fee;//实际提现金额

                //merchant.AcqMerId
                var outTradeNo = Config.GUID();//商户分账订单号

                splitRecord.Id = outTradeNo;
                splitRecord.OutTradeNo = outTradeNo;
                splitRecord.MerchantId = merchant.Id;
                splitRecord.CustomerCode = merchant.AcqSpId;
                splitRecord.MemberId = merchant.AcqMerId;
                splitRecord.UserId = merchant.CreatorId;
                splitRecord.Amount = dto.Amount;
                splitRecord.Fee = fee;
                splitRecord.FeeRate = feeRate;
                splitRecord.ActualAmount = sendAmount;
                splitRecord.SplitStatus = 0;//处理中
                splitRecord.RequestTime = DateTime.Now;
                splitRecord.CreationTime = DateTime.Now;

                var apiBaseUrl = _configuration["PaymentApi:BaseUrl"];
                var url = $"{apiBaseUrl}/api/txs/split/accountSplit";
                var request = new AccountSplitRequest()
                {
                    Version = "1.0",
                    //AttachData = $"分账订单号:{outTradeNo}",
                    CustomerCode = merchant.AcqSpId,
                    OutTradeNo = outTradeNo,
                    CommodityAmount = sendAmount,
                    SplitInfoList = new List<SplitInfo>(),
                    CommodityInfoList = new List<CommodityInfo>(),
                    NotifyUrl = $"{_configuration["SelfUrl"]}/api/Payment/HandleMerchantSplitResultNotification",//通知地址
                    NonceStr = Config.GenerateRandomKey(32)
                };
                request.CommodityInfoList.Add(new CommodityInfo
                {
                    CommodityOrderNo = Config.GUID(),
                    CommodityOrderAmount = sendAmount,
                    CommodityOrderType = "1",
                    CommodityDescription = "提现",
                    CommodityOrderTime = DateTime.Now.ToString("yyyyMMddHHmmss")
                });

                request.SplitInfoList.Add(new SplitInfo
                {
                    Amount = sendAmount,
                    CustomerCode = merchant.AcqMerId,
                    IsProcedureCustomer = 0,
                    SettleCycle = 30
                });

                splitRecord.NonceStr = request.NonceStr;
                splitRecord.NotifyUrl = request.NotifyUrl;
                splitRecord.RequestData = Config.SerializeToJson(request);

                var result = await epaylinksService.post(Config.SerializeToJson(request), url);
                var res = Config.DeserializeFromJson<SplitWithdrawalResponseDto>(result);

                splitRecord.ApiResponse = result;

                int code = res.ReturnCode == "0000" ? 1 : 0;
                if (code == 0)
                    splitRecord.SplitStatus = 2;//分账失败

                //分账成功扣除可提现余额
                if (code == 1)
                {
                    await AddAccountTransactionAsync(new AccountTransactionRequestDto
                    {
                        UserId = splitRecord.UserId,
                        Amount = -splitRecord.Amount,
                        TransactionType = 3,
                        BalanceType = 3,
                        WithdrawalRecordId = splitRecord.Id
                    });
                }

                res.Amount = dto.Amount;
                res.FeeRate = feeRate;
                res.Fee = fee;
                res.SendAmount = sendAmount;
                res.Detail = result;
                res.CreationTime = splitRecord.CreationTime;

                var paper = Config.DeserializeFromJson<EpaylinksPaper>(merchant.Paper);
                res.BankUserName = paper?.SettleAccountInfo?.SettleAccount;
                res.BankCardNo = paper?.SettleAccountInfo?.SettleAccountNo;
                res.BankName = paper?.SettleAccountInfo?.OpenBank;
                res.Phone = merchant.ContactPhone;

                return GetResult(code, message: res.ReturnMsg, data: res);
                //scope.Complete();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                await _paymentIOC._epaylinksSplitRecordEFCore.AddAsync(splitRecord);
                var result = await _paymentIOC._epaylinksSplitRecordEFCore.SaveChangesAsync();
            }

        }

        /// <summary>
        /// 平台方分账并提现
        /// </summary>
        /// <param name="Amount"></param>
        /// <returns></returns>
        public async Task<ApiResult> PlatformSplitWithdrawalAsync(long Amount)
        {
            try
            {
                var merchantId = _configuration["PaymentPlatform:MerchantId"];
                var merchant = await _paymentIOC._merchantEFCore.QueryAll(d => d.Id == merchantId).FirstOrDefaultAsync();
                if (merchant == null)
                {
                    return GetResult(message: "平台商户信息未配置，请联系管理员！");
                }
                //扣除平台可提现余额
                await AddPaymentPlatformTransactionAsync(new AccountTransactionRequestDto
                {
                    PaymentPlatformId = _configuration["PaymentPlatform:PlatformId"],
                    Amount = -Amount,
                    TransactionType = 3,//余额提现
                    BalanceType = 1
                });

                //转入平台商户可提现余额
                await AddAccountTransactionAsync(new AccountTransactionRequestDto
                {
                    UserId = merchant.CreatorId,
                    Amount = Amount,
                    TransactionType = 3,
                    BalanceType = 3,
                    
                });

                var dto = new SplitWithdrawalRequestDto
                {
                    MerId = merchantId,
                    Amount = Amount
                };
                var result = await SplitWithdrawalAsync(dto);
                return result;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 分账结果回调通知
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<EpaylinksResponseDto> HandleMerchantSplitResultNotificationAsync(SplitResultNotificationRequest request)
        {
            try
            {
                var splitRecord = await _paymentIOC._epaylinksSplitRecordEFCore.QueryAll(d => d.Id == request.OutTradeNo).FirstOrDefaultAsync();
                if (splitRecord == null)
                {
                    return new EpaylinksResponseDto
                    {
                        ReturnCode = "0001",
                        ReturnMsg = "未找到对应的分账记录，无法处理回调通知"
                    };
                }

                if (splitRecord.SplitStatus == 0 || splitRecord.SplitStatus == 5)
                {
                    splitRecord.TransactionNo = request.TransactionNo;
                    splitRecord.SplitTransactionNo = request.SplitTransactionNo;
                    splitRecord.OutSplitTradeNo = request.OutSplitTradeNo;
                    splitRecord.RevokeTransactionNo = request.RevokeTransactionNo;
                    splitRecord.RealAmount = request.RealAmount;
                    splitRecord.ProcedureFee = request.ProcedureFee;
                    splitRecord.SplitState = request.SplitState;
                    splitRecord.SplitStatus = Config.ConvertSplitStateToSplitStatus(request.SplitState);
                    splitRecord.SplitTime = Config.ParseTimeString(request.SplitTime);
                    //splitRecord.AttachData = request.AttachData;
                    splitRecord.LastModificationTime = DateTime.Now;
                    splitRecord.CallbackData = Config.SerializeToJson(request);
                    splitRecord.CallbackTime = DateTime.Now;

                    await _paymentIOC._epaylinksSplitRecordEFCore.UpdateAsync(splitRecord);
                    var result = await _paymentIOC._epaylinksSplitRecordEFCore.SaveChangesAsync();

                    //分账成功调用提现
                    if (splitRecord.SplitStatus == 1 || splitRecord.SplitStatus == 3)
                    {
                        await AddSubMerchantWithdrawalRecordAsync(new AddWithdrawalRequest
                        {
                            CustomerCode = splitRecord.CustomerCode,
                            MemberId = splitRecord.MemberId,
                            PayAmount = splitRecord.ActualAmount,
                            UserId = splitRecord.UserId,
                            Amount = splitRecord.Amount,
                            Fee = splitRecord.Fee,
                            FeeRate = splitRecord.FeeRate,
                            ActualAmount = splitRecord.ActualAmount,
                            MerchantId = splitRecord.MerchantId,
                            EpaylinksSplitRecordId = splitRecord.Id
                        });
                    }
                    else
                    {
                        return new EpaylinksResponseDto
                        {
                            ReturnCode = "0001",
                            ReturnMsg = "系统繁忙，更新分账记录失败"
                        };
                    }

                    if (result == 0)
                    {
                        return new EpaylinksResponseDto
                        {
                            ReturnCode = "0001",
                            ReturnMsg = "系统繁忙，更新分账记录失败"
                        };
                    }
                }

                return new EpaylinksResponseDto
                {
                    ReturnCode = "0000",
                    ReturnMsg = "处理成功"
                };
            }
            catch (Exception)
            {
                return new EpaylinksResponseDto
                {
                    ReturnCode = "0001",
                    ReturnMsg = "系统繁忙，更新分账记录失败"
                };
                throw;
            }
        }

        /// <summary>
        /// 商户分账结果查询
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> MerchantSplitResultQueryAsync(SplitResultQueryRequestDto dto)
        {

            try
            {
                var splitRecord = await _paymentIOC._epaylinksSplitRecordEFCore.QueryAll(d => d.Id == dto.OutTradeNo).FirstOrDefaultAsync();
                if (splitRecord == null)
                {
                    return GetResult(message: "未找到对应的分账记录，无法查询结果");
                }
                //var merchant = await _paymentIOC._merchantEFCore.QueryAll(d => d.Id == splitRecord.MerchantId).FirstOrDefaultAsync();
                dto.CustomerCode = splitRecord.CustomerCode;//562294004495976
                dto.NonceStr = splitRecord.NonceStr;
                dto.Version = "2.0";
                var apiBaseUrl = _configuration["PaymentApi:BaseUrl"];
                var url = $"{apiBaseUrl}/api/txs/pay/SplitOrderResultQuery";

                var result = await epaylinksService.post(Config.SerializeToJson(dto), url);
                var res = Config.DeserializeFromJson<EpaylinksResponseDto>(result);

                return GetResult(res.ReturnCode == "0000" ? 1 : 0, message: res.ReturnMsg, data: result);

            }
            catch (Exception)
            {

                throw;
            }


        }

        /// <summary>
        /// 新增分账商户提现记录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddSubMerchantWithdrawalRecordAsync(AddWithdrawalRequest dto)
        {
            WithdrawalRecord withdrawalRecord = new WithdrawalRecord();
            SubMerchantWithdrawalRequest request = new SubMerchantWithdrawalRequest();
            try
            {
                var outTradeNo = Config.GUID();//提现的商户订单号

                if (!string.IsNullOrEmpty(dto.EpaylinksSplitRecordId))
                {
                    var epaylinksSplitRecord = await _paymentIOC._epaylinksSplitRecordEFCore.QueryAll(d => d.Id == dto.EpaylinksSplitRecordId).FirstOrDefaultAsync();
                    if (epaylinksSplitRecord != null)
                    {
                        withdrawalRecord.Id = outTradeNo;
                        withdrawalRecord.UserId = epaylinksSplitRecord.UserId;
                        withdrawalRecord.AccountTransactionId = "";
                        withdrawalRecord.Amount = epaylinksSplitRecord.Amount;
                        withdrawalRecord.Fee = epaylinksSplitRecord.Fee;
                        withdrawalRecord.FeeRate = epaylinksSplitRecord.FeeRate;
                        withdrawalRecord.ActualAmount = epaylinksSplitRecord.ActualAmount;
                        withdrawalRecord.MerchantId = epaylinksSplitRecord.MerchantId;
                        withdrawalRecord.WithdrawalStatus = 0;
                        withdrawalRecord.CreationTime = DateTime.Now;
                        withdrawalRecord.EpaylinksSplitRecordId = dto.EpaylinksSplitRecordId;

                        request.Version = "3.0";
                        request.OutTradeNo = outTradeNo;
                        request.CustomerCode = epaylinksSplitRecord.CustomerCode;
                        request.MemberId = epaylinksSplitRecord.MemberId;
                        request.PayAmount = epaylinksSplitRecord.ActualAmount;
                        request.ArrivalType = 0;
                        request.IsFullAmount = 0;
                        request.PayCurrency = "CNY";
                        request.NotifyUrl = $"{_configuration["SelfUrl"]}/api/Payment/HandleSubMerchantWithdrawalResultNotification";//通知地址;
                        request.NonceStr = Config.GenerateRandomKey(32);
                        request.Remark = "人工";

                        withdrawalRecord.Version = request.Version;
                        withdrawalRecord.CustomerCode = request.CustomerCode;
                        withdrawalRecord.OutTradeNo = request.OutTradeNo;
                        withdrawalRecord.MemberId = request.MemberId;
                        withdrawalRecord.PayAmount = request.PayAmount;
                        withdrawalRecord.ArrivalType = request.ArrivalType;
                        withdrawalRecord.IsFullAmount = request.IsFullAmount;
                        withdrawalRecord.PayCurrency = request.PayCurrency;
                        withdrawalRecord.NotifyUrl = request.NotifyUrl;
                        withdrawalRecord.Remark = request.Remark;
                        withdrawalRecord.NonceStr = request.NonceStr;
                    }
                }
                else
                {
                    withdrawalRecord.Id = outTradeNo;
                    withdrawalRecord.UserId = dto.UserId;
                    withdrawalRecord.AccountTransactionId = "";
                    withdrawalRecord.Amount = dto.Amount;
                    withdrawalRecord.Fee = dto.Fee;
                    withdrawalRecord.FeeRate = dto.FeeRate;
                    withdrawalRecord.ActualAmount = dto.ActualAmount;
                    withdrawalRecord.MerchantId = dto.MerchantId;
                    withdrawalRecord.WithdrawalStatus = 0;
                    withdrawalRecord.CreationTime = DateTime.Now;

                    withdrawalRecord.EpaylinksSplitRecordId = dto.EpaylinksSplitRecordId;

                    request.Version = "3.0";
                    request.OutTradeNo = outTradeNo;
                    request.CustomerCode = dto.CustomerCode;//562294004495976
                    request.MemberId = dto.MemberId;
                    request.PayAmount = dto.PayAmount;
                    request.ArrivalType = 0;
                    request.IsFullAmount = 0;
                    request.PayCurrency = "CNY";
                    request.NotifyUrl = $"{_configuration["SelfUrl"]}/api/Payment/HandleSubMerchantWithdrawalResultNotification";//通知地址
                    request.NonceStr = Config.GenerateRandomKey(32);
                    request.Remark = "自动";

                    withdrawalRecord.Version = request.Version;
                    withdrawalRecord.CustomerCode = request.CustomerCode;
                    withdrawalRecord.OutTradeNo = request.OutTradeNo;
                    withdrawalRecord.MemberId = request.MemberId;
                    withdrawalRecord.PayAmount = request.PayAmount;
                    withdrawalRecord.ArrivalType = request.ArrivalType;
                    withdrawalRecord.IsFullAmount = request.IsFullAmount;
                    withdrawalRecord.PayCurrency = request.PayCurrency;
                    withdrawalRecord.NotifyUrl = request.NotifyUrl;
                    withdrawalRecord.Remark = request.Remark;
                    withdrawalRecord.NonceStr = request.NonceStr;
                }


                withdrawalRecord.RequestData = Config.SerializeToJson(request);

                var apiBaseUrl = _configuration["PaymentApi:BaseUrl"];
                var url = $"{apiBaseUrl}/api/txs/pay/WithdrawalForSubMerchant";

                var result = await epaylinksService.post(Config.SerializeToJson(request), url);
                var res = Config.DeserializeFromJson<SubMerchantWithdrawalResponse>(result);

                withdrawalRecord.ApiResponse = result;
                withdrawalRecord.TransactionNo = res.TransactionNo;
                withdrawalRecord.ProcedureFee = res.ProcedureFee;
                withdrawalRecord.ProcedureCustomerCode = res.ProcedureCustomerCode;
                withdrawalRecord.ActualFee = res.ActualFee;
                withdrawalRecord.PayResult = res.PayResult;
                withdrawalRecord.ChannelQueryMsg = res.ChannelQueryMsg;

                int code = res.ReturnCode == "0000" ? 1 : 0;
                if (code == 0)
                    withdrawalRecord.WithdrawalStatus = 2;//提现失败

                return GetResult(code, message: res.ReturnMsg, data: result);

            }
            catch (Exception)
            {
                throw;
            }
            finally
            {

                await _paymentIOC._withdrawalRecordEFCore.AddAsync(withdrawalRecord);
                var result = await _paymentIOC._withdrawalRecordEFCore.SaveChangesAsync();
            }
        }

        /// <summary>
        /// 分账商户提现结果回调通知
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<EpaylinksResponseDto> HandleSubMerchantWithdrawalResultNotificationAsync(SubMerchantWithdrawalResultNotificationRequestDto dto)
        {
            try
            {
                var withdrawalRecord = await _paymentIOC._withdrawalRecordEFCore.QueryAll(d => d.Id == dto.OutTradeNo).FirstOrDefaultAsync();
                if (withdrawalRecord == null)
                {
                    return new EpaylinksResponseDto
                    {
                        ReturnCode = "0001",
                        ReturnMsg = "未找到对应的提现记录，无法处理回调通知"
                    };
                }

                if (withdrawalRecord.WithdrawalStatus == 0 || withdrawalRecord.WithdrawalStatus == 3)
                {
                    withdrawalRecord.TransactionNo = dto.TransactionNo;
                    withdrawalRecord.PayState = dto.PayState;
                    withdrawalRecord.ServiceFeeState = dto.ServiceFeeState;
                    withdrawalRecord.ProcedureCustomerCode = dto.ProcedureCustomerCode;
                    withdrawalRecord.ProcedureFee = dto.ProcedureFee;
                    withdrawalRecord.PayTime = Config.ParseTimeString(dto.PayTime);
                    withdrawalRecord.ChannelQueryMsg = dto.ChannelQueryMsg;
                    withdrawalRecord.ChannelType = dto.ChannelType;
                    withdrawalRecord.BankName = dto.BankName;
                    withdrawalRecord.BankCardNo = dto.BankCardNo;
                    withdrawalRecord.BankUserName = dto.BankUserName;
                    withdrawalRecord.LastModificationTime = DateTime.Now;
                    withdrawalRecord.CallbackData = Config.SerializeToJson(dto);
                    withdrawalRecord.WithdrawalStatus = Config.ConvertPayStateToWithdrawalStatus(dto.PayState);

                    var merchant = await _paymentIOC._merchantEFCore.QueryAll(d => d.Id == withdrawalRecord.MerchantId).FirstOrDefaultAsync();
                    if (merchant != null)
                    {
                        EpaylinksPaper epaylinksPaper = new EpaylinksPaper();
                        epaylinksPaper = Config.DeserializeFromJson<EpaylinksPaper>(merchant.Paper);
                        withdrawalRecord.BankUserName = epaylinksPaper?.SettleAccountInfo?.SettleAccount;
                    }

                    await _paymentIOC._withdrawalRecordEFCore.UpdateAsync(withdrawalRecord);
                    var result = await _paymentIOC._withdrawalRecordEFCore.SaveChangesAsync();

                    if (withdrawalRecord.WithdrawalStatus != 1)
                    {
                        return new EpaylinksResponseDto
                        {
                            ReturnCode = "0001",
                            ReturnMsg = "系统繁忙，更新提现记录失败"
                        };
                    }
                    else
                    {
                        //提现成功，支付平台收取手续费入账
                        await AddPaymentPlatformTransactionAsync(new AccountTransactionRequestDto
                        {
                            PaymentPlatformId = merchant.PaymentPlatformId ?? _configuration["PaymentPlatform:PlatformId"],
                            Amount = withdrawalRecord.Fee - 20,
                            TransactionType = 11,//提现手续费
                            BalanceType = 1
                        });

                    }

                    if (result == 0)
                    {
                        return new EpaylinksResponseDto
                        {
                            ReturnCode = "0001",
                            ReturnMsg = "系统繁忙，更新提现记录失败"
                        };
                    }

                }

                return new EpaylinksResponseDto
                {
                    ReturnCode = "0000",
                    ReturnMsg = "处理成功"
                };
            }
            catch (Exception)
            {
                return new EpaylinksResponseDto
                {
                    ReturnCode = "0001",
                    ReturnMsg = "系统繁忙，更新提现记录失败"
                };
                throw;
            }

        }

        /// <summary>
        /// 分账商户提现结果查询
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> SubMerchantWithdrawalResultQueryAsync(SubMerchantWithdrawalResultQueryRequestDto dto)
        {
            try
            {
                var withdrawalRecord = await _paymentIOC._withdrawalRecordEFCore.QueryAll(d => d.Id == dto.OutTradeNo).FirstOrDefaultAsync();
                if (withdrawalRecord == null)
                {
                    return GetResult(message: "未找到对应的提现记录，无法查询结果");
                }

                dto.CustomerCode = withdrawalRecord.CustomerCode;
                dto.MemberId = withdrawalRecord.MemberId;
                dto.NonceStr = withdrawalRecord.NonceStr;
                dto.Version = "3.0";

                var apiBaseUrl = _configuration["PaymentApi:BaseUrl"];
                var url = $"{apiBaseUrl}/api/txs/pay/WithdrawalQueryForSubMerchant";

                var result = await epaylinksService.post(Config.SerializeToJson(dto), url);
                var res = Config.DeserializeFromJson<EpaylinksResponseDto>(result);

                return GetResult(res.ReturnCode == "0000" ? 1 : 0, message: res.ReturnMsg, data: result);

            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 获取当前用户提现记录列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetWithdrawalRecordListAsync(BaseRequestDto dto)
        {
            var userId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
            var data = await _paymentIOC._withdrawalRecordEFCore.QueryAll(out int total, dto.Page, dto.Limit, d => d.UserId == userId, d => d.CreationTime, false).ToListAsync();

            return GetResult(1, data: new
            {
                total,
                data
            });
        }

        /// <summary>
        /// 获取单个提现记录详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetWithdrawalRecordDetailAsync(string id)
        { 
            var data = await _paymentIOC._withdrawalRecordEFCore.QueryAll(d => d.Id == id).FirstOrDefaultAsync();
            return GetResult(1, data: data);
        }

        /// <summary>
        /// 新增订单退款记录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddOrderRefundRecordAsync(AddOrderRefundRecordRequestDto dto)
        {
            var permission = await _userService.GetCurUserRolePermissionAsync();
            if (permission != null)
            {
                if (permission.RoleType == 4)
                {
                    return GetResult(message: "当前用户无权限操作，请联系管理员！");
                }
            }
            OrderRefundRecord orderRefundRecord = new OrderRefundRecord();
            RefundRequest refundRequest = new RefundRequest();
            var order = await _paymentIOC._orderEFCore.QueryAll(d => d.Id == dto.OrderId).FirstOrDefaultAsync();
            try
            {

                if (order == null)
                {
                    return GetResult(message: "未找到对应的订单记录，请稍后再试");
                }
                if (!(order.RefundableAmount >= dto.RefundAmount))
                {
                    return GetResult(message: "该订单的可退款金额不足，请重试");
                }
                if (order.PaymentStatus != 1)
                {
                    return GetResult(message: "该订单的状态错误，请重试");
                }
                if (order.IsSettlement == 1)
                {
                    return GetResult(message: "该订单的已结算无法退款，请重试");
                }

                var merchant = await _paymentIOC._merchantEFCore.QueryAll(d => d.Id == order.MerchantId).FirstOrDefaultAsync();
                if (merchant == null)
                {
                    return GetResult(message: "未找到对应的商户信息，请稍后再试");
                }

                var outRefundNo = Config.GUID();//退款订单号
                var nonceStr = Config.GenerateRandomKey(32);

                // 设置退款记录基本信息
                orderRefundRecord.Id = outRefundNo;
                orderRefundRecord.OrderId = order.Id;
                orderRefundRecord.CustomerCode = merchant.AcqSpId;
                orderRefundRecord.OutRefundNo = outRefundNo;
                orderRefundRecord.OutTradeNo = order.OutTradeNo;
                orderRefundRecord.TransactionNo = order.TransactionNo;
                orderRefundRecord.RefundAmount = dto.RefundAmount;
                orderRefundRecord.OriginalAmount = order.PayAmount;
                orderRefundRecord.Status = 0;//处理中
                orderRefundRecord.IsAutoRefund = dto.RefundAmount == order.PayAmount ? true : false;
                orderRefundRecord.NonceStr = nonceStr;
                orderRefundRecord.CreationTime = DateTime.Now;
                orderRefundRecord.NotifyUrl = $"{_configuration["SelfUrl"]}/api/Payment/HandleOrderRefundResultNotification";//退款结果通知地址
                orderRefundRecord.Remark = dto.Remark;

                // 设置退款请求参数
                refundRequest.CustomerCode = order.CustomerCode;
                refundRequest.OutRefundNo = outRefundNo;
                refundRequest.OutTradeNo = order.OutTradeNo;
                refundRequest.TransactionNo = order.TransactionNo;
                refundRequest.RefundAmount = dto.RefundAmount;
                refundRequest.Amount = order.PayAmount;
                refundRequest.NotifyUrl = orderRefundRecord.NotifyUrl;
                refundRequest.NonceStr = nonceStr;
                refundRequest.Remark = dto.Remark;

                // 保存请求参数
                orderRefundRecord.RequestData = Config.SerializeToJson(refundRequest);

                var apiBaseUrl = _configuration["PaymentApi:BaseUrl"];
                var url = $"{apiBaseUrl}/api/txs/pay/Refund/V2";

                var result = await epaylinksService.post(Config.SerializeToJson(refundRequest), url);
                var res = Config.DeserializeFromJson<RefundResponse>(result);

                // 保存API响应
                orderRefundRecord.ApiResponse = result;
                orderRefundRecord.ProcedureFee = res.ProcedureFee;
                orderRefundRecord.BackpayProcedurefee = res.BackpayProcedurefee;
                orderRefundRecord.BackSplitProcedureFee = res.BackSplitProcedureFee;
                orderRefundRecord.TransactionNo = res.TransactionNo;

                int code = res.ReturnCode == "0000" ? 1 : 0;
                if (code == 0)
                {
                    orderRefundRecord.Status = 2;//退款申请失败

                }
                else
                {
                    // 仅标记订单有退款进行中，金额及结果状态待回调成功后更新
                    order.RefundProcessStatus = 1; // 退款处理中
                    await _paymentIOC._orderEFCore.UpdateAsync(order);
                }

                return GetResult(code, message: res.ReturnMsg, data: result);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                await _paymentIOC._orderRefundRecordEFCore.AddAsync(orderRefundRecord);
                var result = await _paymentIOC._orderRefundRecordEFCore.SaveChangesAsync();
            }
        }

        /// <summary>
        /// 订单退款结果回调通知
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<EpaylinksResponseDto> HandleOrderRefundResultNotificationAsync(RefundResultNotificationRequestDto dto)
        {
            try
            {
                // 1) 查找退款记录
                var refundRecord = await _paymentIOC._orderRefundRecordEFCore
                    .QueryAll(d => d.OutRefundNo == dto.OutRefundNo)
                    .FirstOrDefaultAsync();

                if (refundRecord == null)
                {
                    return new EpaylinksResponseDto
                    {
                        ReturnCode = "0001",
                        ReturnMsg = "未找到对应的退款记录，无法处理回调通知"
                    };
                }

                // 2) 幂等：若已是最终状态（成功/失败），直接返回成功
                if (refundRecord.Status == 1 || refundRecord.Status == 2)
                {
                    return new EpaylinksResponseDto
                    {
                        ReturnCode = "0000",
                        ReturnMsg = "处理成功"
                    };
                }

                // 3) 根据 PayState 分支处理
                var payState = dto.PayState?.Trim();

                // 通用回填（不改变最终状态时也可记录）
                refundRecord.TransactionNo = dto.TransactionNo;
                refundRecord.ChannelTradeNo = dto.ChannelTradeNo;
                refundRecord.OutSplitTradeNo = dto.OutSplitTradeNo;
                refundRecord.ProcedureFee = dto.ProcedureFee;
                refundRecord.BackpayProcedurefee = dto.BackpayProcedurefee;
                refundRecord.BackSplitProcedureFee = dto.BackSplitProcedureFee;
                refundRecord.RefundState = dto.PayState;
                refundRecord.RefundTime = Config.ParseTimeString(dto.PayTime);
                refundRecord.RefundDetail = dto.RefundDetail;
                refundRecord.SplitInfoList = dto.SplitInfoList;
                refundRecord.ReturnToList = dto.ReturnToList;
                refundRecord.Reserved = dto.Reserved;
                refundRecord.LastModificationTime = DateTime.Now;
                refundRecord.CallbackData = Config.SerializeToJson(dto);

                if (payState == "00")
                {
                    // 退款成功
                    refundRecord.Status = 1;

                    await _paymentIOC._orderRefundRecordEFCore.UpdateAsync(refundRecord);
                    var saveRefund = await _paymentIOC._orderRefundRecordEFCore.SaveChangesAsync();
                    if (saveRefund == 0)
                    {
                        return new EpaylinksResponseDto
                        {
                            ReturnCode = "0001",
                            ReturnMsg = "系统繁忙，更新退款记录失败"
                        };
                    }

                    // 同步更新订单的退款相关字段
                    var order = await _paymentIOC._orderEFCore
                        .QueryAll(d => d.Id == refundRecord.OrderId)
                        .FirstOrDefaultAsync();

                    if (order == null)
                    {
                        return new EpaylinksResponseDto
                        {
                            ReturnCode = "0001",
                            ReturnMsg = "系统繁忙，更新交易订单失败"
                        };
                    }

                    var curRefund = refundRecord.RefundAmount;
                    var totalRefundBefore = order.TotalRefundAmount ?? 0L;
                    var refundableBefore = order.RefundableAmount ?? 0L;

                    order.TotalRefundAmount = totalRefundBefore + curRefund;
                    order.RefundableAmount = Math.Max(0, refundableBefore - curRefund);
                    order.RefundCount = (order.RefundCount ?? 0) + 1;
                    order.LastRefundTime = refundRecord.RefundTime ?? DateTime.Now;
                    order.RefundProcessStatus = 0; // 无退款在处理
                    order.ProcedureFee = Math.Max(0, (long)(order.ProcedureFee - refundRecord.BackpayProcedurefee)); // 累计扣减已退回的手续费

                    var oldSettlementAmount = order.SettlementAmount ?? 0; // 缓存旧结算金额，用于计算结算差额
                    var totalRefund = order.TotalRefundAmount ?? 0L; // 累计退款金额（含本次），空则视为0
                    var payAmount = order.PayAmount; // 原始实收金额（不含优惠券减免）
                    var netPay = Math.Max(0, payAmount - totalRefund); // 净实收：实收-累计退款，确保非负

                    long updatedCommission = 0; // 初始化重算后的手续费
                    if (string.IsNullOrEmpty(order.CouponInstanceId)) // 未使用优惠券时才计手续费
                    {
                        updatedCommission = (long)(netPay < 100 ? 0 : Math.Ceiling((decimal)netPay * order.Rate)); // 小于1元不收，其他按费率向上取整
                    }

                    var platformFeeRate = order.PlatformServiceFeeRate ?? 0m; // 平台费费率，空则视为0
                    var isCouponUsed = !string.IsNullOrEmpty(order.CouponInstanceId); // 是否使用了优惠券
                    var isFullRefund = totalRefund >= payAmount; // 是否全额退款：累计退款≥实收

                    long updatedPlatformServiceFee = order.PlatformServiceFee ?? 0; // 初始化平台费为当前值
                    long updatedRecommendationCommissionAmount = order.RecommendationCommissionAmount ?? 0; // 初始化推荐分成为当前值

                    bool isSchemeA = false; // 标记是否为A方案（消费者承担）
                    if (isCouponUsed && platformFeeRate > 0m) // 仅在使用优惠券且有费率时尝试判定方案
                    {
                        var expectedA = (long)Math.Ceiling((decimal)order.OrderAmount * platformFeeRate); // A方案平台费=订单金额*费率（向上取整）
                        isSchemeA = expectedA == (order.PlatformServiceFee ?? 0); // 与当前平台费匹配则认为是A方案
                    }

                    if (isCouponUsed) // 使用优惠券时需要重算平台费与推荐分成
                    {
                        if (isFullRefund) // 全额退款：平台费与推荐分成归零
                        {
                            updatedPlatformServiceFee = 0; // 全额退款平台费置零（满足你的业务要求）
                            updatedRecommendationCommissionAmount = 0; // 全额退款推荐分成置零（满足你的业务要求）
                        }
                        else // 部分退款：按A/B方案分别重算
                        {
                            if (isSchemeA) // A方案（消费者承担）：按“订单金额-累计退款”重算平台费
                            {
                                var netOrderAmountForA = Math.Max(0, order.OrderAmount - totalRefund); // A方案平台费基数：订单金额-累计退款，确保非负
                                updatedPlatformServiceFee = (long)Math.Ceiling((decimal)netOrderAmountForA * platformFeeRate); // 平台费=基数*费率，向上取整
                            }
                            else // B方案（商家承担）：按“净实收”重算平台费
                            {
                                updatedPlatformServiceFee = (long)Math.Ceiling((decimal)netPay * platformFeeRate); // 平台费=净实收*费率，向上取整
                            }
                            updatedRecommendationCommissionAmount = string.IsNullOrEmpty(order.RecommendMerchantId) ? 0 : (long)(updatedPlatformServiceFee * 0.05m); // 推荐分成=平台费5%，无推荐商户则为0
                        }
                    }
                    else // 未使用优惠券：平台费与推荐分成均为0
                    {
                        updatedPlatformServiceFee = 0; // 无券订单不计平台费
                        updatedRecommendationCommissionAmount = 0; // 无券订单不计推荐分成
                    }

                    var newSettlementAmount = isFullRefund ? 0 : Math.Max(0, netPay - updatedCommission - updatedPlatformServiceFee); // 新结算金额：全额退款为0；部分退款按净额-手续费-平台费
                    var deltaSettlement = Math.Max(0, oldSettlementAmount - newSettlementAmount); // 结算差额：用于账户扣减，确保非负

                    order.Commission = isFullRefund ? 0 : updatedCommission; // 更新订单手续费：全额退款为0，部分退款为重算值
                    order.PlatformServiceFee = updatedPlatformServiceFee; // 更新平台服务费：按A/B方案重算或归零
                    order.RecommendationCommissionAmount = updatedRecommendationCommissionAmount; // 更新推荐分成：按平台费5%重算或归零
                    order.SettlementAmount = newSettlementAmount; // 更新订单结算金额：新值或0
                    order.RefundStatus = isFullRefund ? 2 : 1; // 更新退款状态：2=全额退款，1=部分退款

                    var merchant = await _paymentIOC._merchantEFCore.QueryAll(d => d.Id == order.MerchantId).FirstOrDefaultAsync(); // 查询商户，用于后续账户扣减
                    if (string.IsNullOrEmpty(order.DividedAgreementId)) // 无分账协议：扣“待结算余额”
                    {
                        await AddAccountTransactionAsync(new AccountTransactionRequestDto // 扣减仅按结算差额，防止负数
                        {
                            UserId = merchant.CreatorId, // 商户主账户
                            Amount = -deltaSettlement, // 扣减金额为负（结算差额）
                            OrderId = order.Id, // 关联订单
                            TransactionType = 2, // 交易类型：退款
                            BalanceType = 4, // 余额类型：待结算
                        });
                    }
                    else // 有分账协议：扣“待分账余额”
                    {
                        await AddAccountTransactionAsync(new AccountTransactionRequestDto // 扣减仅按结算差额，防止负数
                        {
                            UserId = merchant.CreatorId, // 商户主账户
                            Amount = -deltaSettlement, // 扣减金额为负（结算差额）
                            OrderId = order.Id, // 关联订单
                            TransactionType = 2, // 交易类型：退款
                            BalanceType = 5, // 余额类型：待分账
                        });
                    }

                    //// 新增：基于净额重算手续费与结算金额
                    //// 先缓存旧结算金额，避免直接用退款额扣减造成负数
                    //var oldSettlementAmount = order.SettlementAmount ?? 0;
                    //var netPay = Math.Max(0, (order.PayAmount) - (order.TotalRefundAmount ?? 0));
                    ////使用优惠券则不计算手续费
                    //long updatedCommission = 0;
                    //if (string.IsNullOrEmpty(order.CouponInstanceId))
                    //{
                    //    updatedCommission = (long)(netPay < 100 ? 0 : Math.Ceiling((decimal)netPay * order.Rate));
                    //}
                    //var platformFee = order.PlatformServiceFee ?? 0; // 如需按费率重算，可改为按 PlatformServiceFeeRate
                    //var newSettlementAmount = Math.Max(0, netPay - updatedCommission - platformFee);
                    //var deltaSettlement = Math.Max(0, oldSettlementAmount - newSettlementAmount);

                    //order.Commission = updatedCommission;
                    //order.SettlementAmount = Math.Max(0, netPay - updatedCommission - platformFee);

                    //var merchant = await _paymentIOC._merchantEFCore.QueryAll(d => d.Id == order.MerchantId).FirstOrDefaultAsync();
                    //if (string.IsNullOrEmpty(order.DividedAgreementId))
                    //{
                    //    //退款成功扣除待结算余额
                    //    await AddAccountTransactionAsync(new AccountTransactionRequestDto
                    //    {
                    //        UserId = merchant.CreatorId,
                    //        Amount = -deltaSettlement,
                    //        OrderId = order.Id,
                    //        TransactionType = 2,
                    //        BalanceType = 4, //待结算
                    //    });
                    //}
                    //else
                    //{
                    //    //退款成功扣除待分账余额
                    //    await AddAccountTransactionAsync(new AccountTransactionRequestDto
                    //    {
                    //        UserId = merchant.CreatorId,
                    //        Amount = -deltaSettlement,
                    //        OrderId = order.Id,
                    //        TransactionType = 2,
                    //        BalanceType = 5, //待分账
                    //    });
                    //}

                    //if ((order.TotalRefundAmount ?? 0) >= order.PayAmount)
                    //    order.RefundStatus = 2; // 全额退款
                    //else
                    //    order.RefundStatus = 1; // 部分退款

                    await _paymentIOC._orderEFCore.UpdateAsync(order);
                    var saveOrder = await _paymentIOC._orderEFCore.SaveChangesAsync();
                    if (saveOrder == 0)
                    {
                        return new EpaylinksResponseDto
                        {
                            ReturnCode = "0001",
                            ReturnMsg = "系统繁忙，更新交易订单失败"
                        };
                    }

                    return new EpaylinksResponseDto
                    {
                        ReturnCode = "0000",
                        ReturnMsg = "处理成功"
                    };
                }
                else if (payState == "01")
                {
                    // 退款失败（只更新退款记录，订单金额类字段不变）
                    refundRecord.Status = 2;

                    await _paymentIOC._orderRefundRecordEFCore.UpdateAsync(refundRecord);
                    var saveRefund = await _paymentIOC._orderRefundRecordEFCore.SaveChangesAsync();
                    if (saveRefund == 0)
                    {
                        return new EpaylinksResponseDto
                        {
                            ReturnCode = "0001",
                            ReturnMsg = "系统繁忙，更新退款记录失败"
                        };
                    }

                    // 同步更新订单的退款相关字段
                    var order = await _paymentIOC._orderEFCore
                        .QueryAll(d => d.Id == refundRecord.OrderId)
                        .FirstOrDefaultAsync();

                    if (order == null)
                    {
                        return new EpaylinksResponseDto
                        {
                            ReturnCode = "0001",
                            ReturnMsg = "系统繁忙，更新交易订单失败"
                        };
                    }
                    order.RefundCount = (order.RefundCount ?? 0) + 1;
                    order.LastRefundTime = refundRecord.RefundTime ?? DateTime.Now;
                    order.RefundProcessStatus = 0; // 无退款在处理

                    await _paymentIOC._orderEFCore.UpdateAsync(order);
                    var saveOrder = await _paymentIOC._orderEFCore.SaveChangesAsync();

                    if (saveOrder == 0)
                    {
                        return new EpaylinksResponseDto
                        {
                            ReturnCode = "0001",
                            ReturnMsg = "系统繁忙，更新交易订单失败"
                        };
                    }

                    return new EpaylinksResponseDto
                    {
                        ReturnCode = "0000",
                        ReturnMsg = "处理成功"
                    };
                }
                else
                {
                    // 退款处理中（03）或未知状态：不改变最终状态，要求重试
                    // 保持 refundRecord.Status 不变（仍为 0=处理中），但保留回调数据
                    await _paymentIOC._orderRefundRecordEFCore.UpdateAsync(refundRecord);
                    await _paymentIOC._orderRefundRecordEFCore.SaveChangesAsync();

                    return new EpaylinksResponseDto
                    {
                        ReturnCode = "0001",
                        ReturnMsg = "退款处理中，等待后续通知"
                    };
                }
            }
            catch (Exception)
            {
                return new EpaylinksResponseDto
                {
                    ReturnCode = "0001",
                    ReturnMsg = "系统繁忙，更新退款记录失败"
                };
                throw;
            }
        }

        /// <summary>
        /// 订单退款结果查询
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> OrderRefundRecordQueryAsync(RefundResultQueryRequestDto dto)
        {
            try
            {
                var orderRefundRecord = await _paymentIOC._orderRefundRecordEFCore.QueryAll(d => d.Id == dto.OutRefundNo).FirstOrDefaultAsync();
                if (orderRefundRecord == null)
                {
                    return GetResult(message: "未找到对应的退款记录，无法查询结果");
                }

                dto.CustomerCode = orderRefundRecord.CustomerCode;
                dto.OutRefundNo = orderRefundRecord.OutRefundNo;
                dto.NonceStr = orderRefundRecord.NonceStr;

                var apiBaseUrl = _configuration["PaymentApi:BaseUrl"];
                var url = $"{apiBaseUrl}/api/txs/custPay/refundQuery";

                var result = await epaylinksService.post(Config.SerializeToJson(dto), url);
                var res = Config.DeserializeFromJson<RefundResultQueryResponseDto>(result);

                return GetResult(res.ReturnCode == "0000" ? 1 : 0, message: res.ReturnMsg, data: res);

            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 获取订单退款记录列表
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetOrderRefundRecordListAsync(string orderId)
        {
            var data = await _paymentIOC._orderRefundRecordEFCore.QueryAll(d => d.OrderId == orderId, d => d.CreationTime, false)
                .Select(d => new OrderRefundRecordResponseDto
                {
                    Id = d.Id,
                    OrderId = d.OrderId,
                    CustomerCode = d.CustomerCode,
                    OutRefundNo = d.OutRefundNo,
                    OutTradeNo = d.OutTradeNo,
                    TransactionNo = d.TransactionNo,
                    RefundAmount = d.RefundAmount,
                    OriginalAmount = d.OriginalAmount,
                    Remark = d.Remark,
                    ProcedureFee = d.ProcedureFee,
                    RefundTime = d.RefundTime,
                    ChannelTradeNo = d.ChannelTradeNo,
                    Status = d.Status,
                    IsAutoRefund = d.IsAutoRefund,
                    CreationTime = d.CreationTime,
                    LastModificationTime = d.LastModificationTime,
                    ExtraProperties = d.ExtraProperties
                }).ToListAsync();
            return GetResult(1, data: data);
        }

        /// <summary>
        /// 获取报表数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetReportFormAsync(ReportFormRequestDto dto)
        {
            try
            {
                var permission = await _userService.GetCurUserRolePermissionAsync();
                List<string> storeIds = new List<string>();
                if (permission != null)
                {
                    if (permission.RoleType == 4 || permission.RoleType == 5)//监事/店长
                    {
                        storeIds = permission.StoreIds;
                        if (storeIds.Count() < 1)
                            return GetResult(1, "无关联数据");
                    }

                    if (storeIds.Count == 0 && !string.IsNullOrEmpty(dto.StoreId))
                        storeIds.Add(dto.StoreId);
                }

                if (dto.SelectDateTime == DateTime.MinValue)
                    dto.SelectDateTime = DateTime.Now;

                var reportFormDateTime = new DateTimeRequestDto();
                var reportFormData = new List<DateTimeRequestDto>();
                if (dto.ReportFormType == 0)
                {
                    reportFormDateTime = Config.GetDayRange(dto.SelectDateTime);
                    reportFormData = Config.GetRecentDays(dto.SelectDateTime); // 近7天
                }
                else if (dto.ReportFormType == 1)
                {
                    reportFormDateTime = Config.GetWeekRange(dto.SelectDateTime);
                    reportFormData = Config.GetRecentWeeks(dto.SelectDateTime); // 近4周，含本周
                }
                else if (dto.ReportFormType == 2)
                {
                    reportFormDateTime = Config.GetMonthRange(dto.SelectDateTime);
                    reportFormData = Config.GetRecent6Months(dto.SelectDateTime); // 近6月，含本月
                }

                // 趋势统计范围（用于读取订单）
                var rangeStart = reportFormData.First().StartTime;
                var rangeEnd = reportFormData.Last().EndTime;

                // 基础查询（只查必要字段，且不跟踪）
                var baseQuery = _paymentIOC._orderEFCore.QueryAll(d =>
                        (string.IsNullOrEmpty(dto.MerchantId) || d.MerchantId.Contains(dto.MerchantId))
                        && (!storeIds.Any() || storeIds.Contains(d.StoreId))
                        && d.PaymentStatus == 1
                        && d.CreationTime >= rangeStart && d.CreationTime <= rangeEnd
                    )
                    .AsNoTracking()
                    .Select(d => new
                    {
                        d.Id,
                        d.CreationTime,
                        d.PayAmount,
                        d.TotalRefundAmount,
                        d.SettlementAmount,
                        d.DiscountAmount,
                        d.RefundStatus,
                        d.CodeId,
                        d.CouponInstanceId
                    });

                // 单个区间汇总（在数据库端聚合）
                var singleAgg = await _paymentIOC._orderEFCore.QueryAll(d =>
                            (string.IsNullOrEmpty(dto.MerchantId) || d.MerchantId.Contains(dto.MerchantId)) &&
                            (string.IsNullOrEmpty(dto.StoreId) || d.StoreId.Contains(dto.StoreId)) &&
                            d.PaymentStatus == 1 &&
                            d.CreationTime >= reportFormDateTime.StartTime && d.CreationTime <= reportFormDateTime.EndTime
                        )
                        .AsNoTracking()
                        .GroupBy(_ => 1)
                        .Select(g => new
                        {
                            ActualReceivedAmount = (long)g.Sum(x => (decimal?)x.PayAmount ?? 0),    // 实收金额（单位分）
                            CollectedCount = g.Count(x => x.PaymentStatus == 1),                   // 收款笔数
                            RefundAmount = (long)g.Sum(x => (decimal?)x.TotalRefundAmount ?? 0),   // 退款金额（单位分）
                            RefundCount = g.Count(x => x.RefundStatus == 1 || x.RefundStatus == 2),// 退款笔数（含部分/全额）
                            SettlementAmount = (long)g.Sum(x => (decimal?)x.SettlementAmount ?? 0),// 结算金额（单位分）
                            CouponAmount = (long)g.Sum(x => (decimal?)x.DiscountAmount ?? 0)       // 优惠金额（单位分）
                        })
                        .FirstOrDefaultAsync() ?? new
                        {
                            ActualReceivedAmount = 0L,
                            CollectedCount = 0,
                            RefundAmount = 0L,
                            RefundCount = 0,
                            SettlementAmount = 0L,
                            CouponAmount = 0L
                        };

                var data = new ReportFormRequestDto
                {
                    ActualReceivedAmount = singleAgg.ActualReceivedAmount,
                    CollectedCount = singleAgg.CollectedCount,
                    RefundAmount = singleAgg.RefundAmount,
                    RefundCount = singleAgg.RefundCount,
                    SettlementAmount = singleAgg.SettlementAmount,
                    CouponAmount = singleAgg.CouponAmount
                };
                data.CollectedAmount = data.ActualReceivedAmount - data.RefundAmount;
                data.ActualReceivedAmount = data.CollectedAmount; // 界面显示“实收”即为“净收”（实收-退款）
                // 趋势与优惠统计
                if (dto.ReportFormType == 0)
                {
                    // 按“日”聚合（数据库端）
                    var trendAgg = await baseQuery
                        .GroupBy(x => x.CreationTime.Date)
                        .Select(g => new
                        {
                            Key = g.Key,
                            Amount = (long)g.Sum(x => x.PayAmount) - (long)g.Sum(x => x.TotalRefundAmount),//(long)g.Sum(x => (decimal?)x.PayAmount ?? 0),
                            DiscountedOrderCount = g.Count(x => !string.IsNullOrEmpty(x.CouponInstanceId)),
                            OrderCount = g.Count()
                        })
                        .ToListAsync();

                    foreach (var item in reportFormData)
                    {
                        var dayKey = item.StartTime.Date;
                        var cur = trendAgg.FirstOrDefault(t => t.Key == dayKey);

                        data.IncomeComparisonStatistics.Add(new IncomeComparisonStatisticsRequestDto
                        {
                            StartTime = item.StartTime,
                            EndTime = item.EndTime,
                            Amount = cur?.Amount ?? 0
                        });

                        data.DiscountedOrders.Add(new DiscountedOrdersRequestDto
                        {
                            StartTime = item.StartTime,
                            EndTime = item.EndTime,
                            DiscountedOrderCount = cur?.DiscountedOrderCount ?? 0,
                            OrderCount = cur?.OrderCount ?? 0
                        });
                    }
                }
                else if (dto.ReportFormType == 1)
                {
                    // 按“周”聚合（数据库端：按周首日分组）
                    // 说明：
                    // - Config.GetWeekRange 以周一为周首，数据库端分组也以周一为键，确保与 reportFormData 对齐。
                    // - 分组键使用周首日（00:00:00）的时间戳，便于与 item.StartTime 直接匹配。
                    var trendAggWeek = await _paymentIOC._orderEFCore.QueryAll(d =>
                                (string.IsNullOrEmpty(dto.MerchantId) || d.MerchantId.Contains(dto.MerchantId)) &&
                                (!storeIds.Any() || storeIds.Contains(d.StoreId)) &&
                                d.PaymentStatus == 1 &&
                                d.CreationTime >= rangeStart && d.CreationTime <= rangeEnd
                            )
                            .AsNoTracking()
                            .GroupBy(d =>
                                // 以周一为周首，计算该订单所属周的“周首日”
                                // 公式：周首日 = date(CreationTime) - 偏移天数；偏移= (DayOfWeek - Monday + 7) % 7
                                new DateTime(
                                    d.CreationTime.AddDays(-((int)d.CreationTime.DayOfWeek - (int)DayOfWeek.Monday + 7) % 7).Year,
                                    d.CreationTime.AddDays(-((int)d.CreationTime.DayOfWeek - (int)DayOfWeek.Monday + 7) % 7).Month,
                                    d.CreationTime.AddDays(-((int)d.CreationTime.DayOfWeek - (int)DayOfWeek.Monday + 7) % 7).Day
                                )
                            )
                            .Select(g => new
                            {
                                Key = g.Key, // 周首日（周一 00:00:00）
                                Amount = (long)g.Sum(x => x.PayAmount) - (long)g.Sum(x => x.TotalRefundAmount),//(long)g.Sum(x => (decimal?)x.PayAmount ?? 0),
                                DiscountedOrderCount = g.Count(x => !string.IsNullOrEmpty(x.CouponInstanceId)),
                                OrderCount = g.Count()
                            })
                            .ToListAsync();

                    foreach (var item in reportFormData)
                    {
                        // 与 Config.GetWeekRange 的 StartTime 对齐（周一 00:00:00）
                        var weekKey = item.StartTime.Date;
                        var cur = trendAggWeek.FirstOrDefault(t => t.Key == weekKey);

                        data.IncomeComparisonStatistics.Add(new IncomeComparisonStatisticsRequestDto
                        {
                            StartTime = item.StartTime,
                            EndTime = item.EndTime,
                            Amount = cur?.Amount ?? 0
                        });

                        data.DiscountedOrders.Add(new DiscountedOrdersRequestDto
                        {
                            StartTime = item.StartTime,
                            EndTime = item.EndTime,
                            DiscountedOrderCount = cur?.DiscountedOrderCount ?? 0,
                            OrderCount = cur?.OrderCount ?? 0
                        });
                    }
                }
                else if (dto.ReportFormType == 2)
                {
                    // 按“月”聚合（数据库端，按月首日分组）
                    var trendAggMonth = await baseQuery
                        .GroupBy(x => new DateTime(x.CreationTime.Year, x.CreationTime.Month, 1))
                        .Select(g => new
                        {
                            Key = g.Key, // 月首日
                            Amount = (long)g.Sum(x => x.PayAmount) - (long)g.Sum(x => x.TotalRefundAmount),//(long)g.Sum(x => (decimal?)x.PayAmount ?? 0),
                            DiscountedOrderCount = g.Count(x => !string.IsNullOrEmpty(x.CouponInstanceId)),
                            OrderCount = g.Count()
                        })
                        .ToListAsync();

                    foreach (var item in reportFormData)
                    {
                        var monthKey = new DateTime(item.StartTime.Year, item.StartTime.Month, 1);
                        var cur = trendAggMonth.FirstOrDefault(t => t.Key == monthKey);

                        data.IncomeComparisonStatistics.Add(new IncomeComparisonStatisticsRequestDto
                        {
                            StartTime = item.StartTime,
                            EndTime = item.EndTime,
                            Amount = cur?.Amount ?? 0
                        });

                        data.DiscountedOrders.Add(new DiscountedOrdersRequestDto
                        {
                            StartTime = item.StartTime,
                            EndTime = item.EndTime,
                            DiscountedOrderCount = cur?.DiscountedOrderCount ?? 0,
                            OrderCount = cur?.OrderCount ?? 0
                        });
                    }
                }

                // 收款码排行榜（数据库端聚合，Top 5）
                var rankingAgg = await _paymentIOC._orderEFCore.QueryAll(d =>
                            (string.IsNullOrEmpty(dto.MerchantId) || d.MerchantId.Contains(dto.MerchantId)) &&
                            (string.IsNullOrEmpty(dto.StoreId) || d.StoreId.Contains(dto.StoreId)) &&
                            d.PaymentStatus == 1 &&
                            d.CreationTime >= reportFormDateTime.StartTime && d.CreationTime <= reportFormDateTime.EndTime &&
                            d.CodeId != null
                        )
                        .AsNoTracking()
                        .GroupBy(d => d.CodeId)
                        .Select(g => new
                        {
                            CodeId = g.Key,
                            Amount = (long)g.Sum(x => x.PayAmount) - (long)g.Sum(x => x.TotalRefundAmount) //(long)g.Sum(x => (decimal?)x.PayAmount ?? 0)
                        })
                        .OrderByDescending(x => x.Amount)
                        .Take(5)
                        .ToListAsync();

                var codeIds = rankingAgg.Select(x => x.CodeId!).ToList();
                var paymentCodes = await _paymentIOC._paymentCodeEFCore.QueryAll(d => codeIds.Contains(d.Id))
                    .AsNoTracking()
                    .Select(d => new { d.Id, d.Code, d.CodeName })
                    .ToListAsync();

                data.PaymentCodeRanking = rankingAgg
                    .Join(paymentCodes, a => a.CodeId, c => c.Id, (a, c) => new PaymentCodeRankingRequestDto
                    {
                        PaymentCodeId = c.Id,
                        Code = c.Code,
                        PaymentCodeName = c.CodeName,
                        Amount = a.Amount
                    })
                    .OrderByDescending(d => d.Amount)
                    .ToList();

                // 支付方式总金额统计（与排行统计口径一致：ΣPayAmount - ΣTotalRefundAmount）
                var wechatAgg = await _paymentIOC._orderEFCore.QueryAll(d =>
                            (string.IsNullOrEmpty(dto.MerchantId) || d.MerchantId.Contains(dto.MerchantId)) &&
                            (string.IsNullOrEmpty(dto.StoreId) || d.StoreId.Contains(dto.StoreId)) &&
                            d.PaymentStatus == 1 &&
                            d.CreationTime >= reportFormDateTime.StartTime && d.CreationTime <= reportFormDateTime.EndTime &&
                            (d.PayMethod == "1" || d.PayMethod == "6" || d.PayMethod == "35")
                        )
                        .AsNoTracking()
                        .Select(x => new { x.PayAmount, x.TotalRefundAmount })
                        .ToListAsync();
                data.WechatAmount = (long)wechatAgg.Sum(x => x.PayAmount) - (long)wechatAgg.Sum(x => x.TotalRefundAmount);
                data.WechatCount = wechatAgg.Count;

                var alipayAgg = await _paymentIOC._orderEFCore.QueryAll(d =>
                            (string.IsNullOrEmpty(dto.MerchantId) || d.MerchantId.Contains(dto.MerchantId)) &&
                            (string.IsNullOrEmpty(dto.StoreId) || d.StoreId.Contains(dto.StoreId)) &&
                            d.PaymentStatus == 1 &&
                            d.CreationTime >= reportFormDateTime.StartTime && d.CreationTime <= reportFormDateTime.EndTime &&
                            (d.PayMethod == "7" || d.PayMethod == "99")
                        )
                        .AsNoTracking()
                        .Select(x => new { x.PayAmount, x.TotalRefundAmount })
                        .ToListAsync();
                data.AlipayAmount = (long)alipayAgg.Sum(x => x.PayAmount) - (long)alipayAgg.Sum(x => x.TotalRefundAmount);
                data.AlipayCount = alipayAgg.Count;

                // 仅用于“分账对比统计”的基础查询（筛选 DividedAgreementId 非空）
                var baseDividedQuery = _paymentIOC._orderEFCore.QueryAll(d =>
                        (string.IsNullOrEmpty(dto.MerchantId) || d.MerchantId.Contains(dto.MerchantId))
                        && (!storeIds.Any() || storeIds.Contains(d.StoreId))
                        && d.PaymentStatus == 1
                        && !string.IsNullOrEmpty(d.DividedAgreementId)
                        && d.CreationTime >= rangeStart && d.CreationTime <= rangeEnd
                    )
                    .AsNoTracking()
                    .Select(d => new
                    {
                        d.CreationTime,
                        d.SettlementAmount
                    });

                if (dto.ReportFormType == 0)
                {
                    // 日维度：按日期分组
                    var dividedTrendDay = await baseDividedQuery
                        .GroupBy(x => x.CreationTime.Date)
                        .Select(g => new
                        {
                            Key = g.Key,
                            Amount = (long)g.Sum(x => (decimal?)x.SettlementAmount ?? 0)
                        })
                        .ToListAsync();

                    foreach (var item in reportFormData)
                    {
                        var dayKey = item.StartTime.Date;
                        var cur = dividedTrendDay.FirstOrDefault(t => t.Key == dayKey);
                        data.DividedAmountComparisonStatistics.Add(new IncomeComparisonStatisticsRequestDto
                        {
                            StartTime = item.StartTime,
                            EndTime = item.EndTime,
                            Amount = cur?.Amount ?? 0
                        });
                    }
                }
                else if (dto.ReportFormType == 1)
                {
                    // 周维度：以周一为周首分组
                    var dividedTrendWeek = await _paymentIOC._orderEFCore.QueryAll(d =>
                                (string.IsNullOrEmpty(dto.MerchantId) || d.MerchantId.Contains(dto.MerchantId))
                                && (!storeIds.Any() || storeIds.Contains(d.StoreId))
                                && d.PaymentStatus == 1
                                && !string.IsNullOrEmpty(d.DividedAgreementId)
                                && d.CreationTime >= rangeStart && d.CreationTime <= rangeEnd
                            )
                            .AsNoTracking()
                            .GroupBy(d => new DateTime(
                                d.CreationTime.AddDays(-((int)d.CreationTime.DayOfWeek - (int)DayOfWeek.Monday + 7) % 7).Year,
                                d.CreationTime.AddDays(-((int)d.CreationTime.DayOfWeek - (int)DayOfWeek.Monday + 7) % 7).Month,
                                d.CreationTime.AddDays(-((int)d.CreationTime.DayOfWeek - (int)DayOfWeek.Monday + 7) % 7).Day
                            ))
                            .Select(g => new
                            {
                                Key = g.Key,
                                Amount = (long)g.Sum(x => (decimal?)x.SettlementAmount ?? 0)
                            })
                            .ToListAsync();

                    foreach (var item in reportFormData)
                    {
                        var weekKey = item.StartTime.Date;
                        var cur = dividedTrendWeek.FirstOrDefault(t => t.Key == weekKey);
                        data.DividedAmountComparisonStatistics.Add(new IncomeComparisonStatisticsRequestDto
                        {
                            StartTime = item.StartTime,
                            EndTime = item.EndTime,
                            Amount = cur?.Amount ?? 0
                        });
                    }
                }
                else if (dto.ReportFormType == 2)
                {
                    // 月维度：按月首日分组
                    var dividedTrendMonth = await baseDividedQuery
                        .GroupBy(x => new DateTime(x.CreationTime.Year, x.CreationTime.Month, 1))
                        .Select(g => new
                        {
                            Key = g.Key,
                            Amount = (long)g.Sum(x => (decimal?)x.SettlementAmount ?? 0)
                        })
                        .ToListAsync();

                    foreach (var item in reportFormData)
                    {
                        var monthKey = new DateTime(item.StartTime.Year, item.StartTime.Month, 1);
                        var cur = dividedTrendMonth.FirstOrDefault(t => t.Key == monthKey);
                        data.DividedAmountComparisonStatistics.Add(new IncomeComparisonStatisticsRequestDto
                        {
                            StartTime = item.StartTime,
                            EndTime = item.EndTime,
                            Amount = cur?.Amount ?? 0
                        });
                    }
                }

                // 顾客识别与首次下单时间（趋势窗口内）
                var customerOrdersForTrend = await _paymentIOC._orderEFCore.QueryAll(d =>
                        (string.IsNullOrEmpty(dto.MerchantId) || d.MerchantId.Contains(dto.MerchantId))
                        && (!storeIds.Any() || storeIds.Contains(d.StoreId))
                        && d.PaymentStatus == 1
                        && d.CreationTime >= rangeStart && d.CreationTime <= rangeEnd
                    )
                    .AsNoTracking()
                    .Select(d => new
                    {
                        d.CreationTime,
                        CustomerId = string.IsNullOrEmpty(d.OpenId) ? d.BuyerId : d.OpenId
                    })
                    .Where(x => !string.IsNullOrEmpty(x.CustomerId))
                    .ToListAsync();

                var customerFirstMap = customerOrdersForTrend
                    .GroupBy(x => x.CustomerId)
                    .ToDictionary(g => g.Key, g => g.Min(x => x.CreationTime));

                // 按筛选类型填充新老顾客统计
                if (dto.ReportFormType == 0)
                {
                    foreach (var item in reportFormData)
                    {
                        var periodCustomers = customerOrdersForTrend
                            .Where(x => x.CreationTime >= item.StartTime && x.CreationTime <= item.EndTime)
                            .Select(x => x.CustomerId)
                            .Distinct()
                            .ToList();

                        var newCount = periodCustomers.Count(id =>
                            customerFirstMap.TryGetValue(id, out var firstTime) && firstTime >= item.StartTime && firstTime <= item.EndTime);
                        var oldCount = periodCustomers.Count - newCount;

                        data.CustomerComparisonStatistics.Add(new CustomerComparisonRequestDto
                        {
                            StartTime = item.StartTime,
                            EndTime = item.EndTime,
                            NewCustomerCount = newCount,
                            OldCustomerCount = oldCount
                        });
                    }
                }
                else if (dto.ReportFormType == 1)
                {
                    foreach (var item in reportFormData)
                    {
                        var periodCustomers = customerOrdersForTrend
                            .Where(x => x.CreationTime >= item.StartTime && x.CreationTime <= item.EndTime)
                            .Select(x => x.CustomerId)
                            .Distinct()
                            .ToList();

                        var newCount = periodCustomers.Count(id =>
                            customerFirstMap.TryGetValue(id, out var firstTime) && firstTime >= item.StartTime && firstTime <= item.EndTime);
                        var oldCount = periodCustomers.Count - newCount;

                        data.CustomerComparisonStatistics.Add(new CustomerComparisonRequestDto
                        {
                            StartTime = item.StartTime,
                            EndTime = item.EndTime,
                            NewCustomerCount = newCount,
                            OldCustomerCount = oldCount
                        });
                    }
                }
                else if (dto.ReportFormType == 2)
                {
                    foreach (var item in reportFormData)
                    {
                        var periodCustomers = customerOrdersForTrend
                            .Where(x => x.CreationTime >= item.StartTime && x.CreationTime <= item.EndTime)
                            .Select(x => x.CustomerId)
                            .Distinct()
                            .ToList();

                        var newCount = periodCustomers.Count(id =>
                            customerFirstMap.TryGetValue(id, out var firstTime) && firstTime >= item.StartTime && firstTime <= item.EndTime);
                        var oldCount = periodCustomers.Count - newCount;

                        data.CustomerComparisonStatistics.Add(new CustomerComparisonRequestDto
                        {
                            StartTime = item.StartTime,
                            EndTime = item.EndTime,
                            NewCustomerCount = newCount,
                            OldCustomerCount = oldCount
                        });
                    }
                }

                return GetResult(1, data: data);
            }
            catch (Exception)
            {
                throw;
            }

        }

        /// <summary>
        /// 获取收款记录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetCollectionRecordListAsync(ReportFormRequestDto dto)
        {
            var permission = await _userService.GetCurUserRolePermissionAsync();
            List<string> storeIds = new List<string>();
            List<string> codeIds = new List<string>();
            if (permission != null)
            {
                if (permission.RoleType == 4 || permission.RoleType == 5)//监事/店长
                {
                    storeIds = permission.StoreIds;
                    if (storeIds.Count() < 1)
                        return GetResult(1, "无关联数据");
                }
                else if (permission.RoleType == 6)//收银员
                {
                    codeIds = permission.CodeIds;
                    if (codeIds.Count() < 1)
                        return GetResult(1, "无关联数据");
                }

                if (storeIds.Count == 0 && !string.IsNullOrEmpty(dto.StoreId))
                    storeIds.Add(dto.StoreId);
                if (codeIds.Count == 0 && !string.IsNullOrEmpty(dto.CodeId))
                    codeIds.Add(dto.CodeId);
            }

            var reportFormData = Config.GetDateRangeList((DateTime)dto.BeginTime, (DateTime)dto.EndTime).OrderByDescending(d => d.StartTime).ToList();

            List<CollectionRecordRequestDto> data = new List<CollectionRecordRequestDto>();

            foreach (var item in reportFormData)
            {
                var orders = await _paymentIOC._orderEFCore.QueryAll(d => (string.IsNullOrEmpty(dto.MerchantId) || d.MerchantId.Contains(dto.MerchantId))
                    && (!storeIds.Any() || storeIds.Contains(d.StoreId))
                    && (!codeIds.Any() || codeIds.Contains(d.CodeId))
                    && (d.CreationTime >= item.StartTime && d.CreationTime <= item.EndTime)
                    && d.PaymentStatus == 1
                   )
                    .AsNoTracking()
                    .GroupBy(_ => 1)  // 全局聚合所有记录
                    .Select(d => new
                    {
                        CollectedAmount = (long)d.Sum(x => x.PayAmount) - (long)d.Sum(x => x.TotalRefundAmount),
                        CollectedCount = d.Count(),
                        CustomerCount = d.Where(x => !string.IsNullOrEmpty(x.OpenId)).Select(x => x.OpenId).Distinct().Count() + d.Where(x => string.IsNullOrEmpty(x.OpenId)).Count(),
                    }).FirstOrDefaultAsync() ?? new
                    {
                        CollectedAmount = 0L,
                        CollectedCount = 0,
                        CustomerCount = 0,
                    };

                var collectionRecord = new CollectionRecordRequestDto
                {
                    DayDate = item.StartTime.Date,
                    CollectedAmount = orders.CollectedAmount,
                    CollectedCount = orders.CollectedCount,
                    CustomerCount = orders.CustomerCount
                };

                data.Add(collectionRecord);

            }

            return GetResult(1, data: data);

        }

        /// <summary>
        /// 获取今日营业额
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetTodayTurnoverAsync(TodayTurnoverRequestDto dto)
        {
            var permission = await _userService.GetCurUserRolePermissionAsync();
            List<string> storeIds = new List<string>();
            List<string> codeIds = new List<string>();
            if (permission != null)
            {
                if (permission.RoleType == 4 || permission.RoleType == 5)//监事/店长
                {
                    storeIds = permission.StoreIds;
                    if (storeIds.Count() < 1)
                        return GetResult(1, "无关联数据");
                }
                else if (permission.RoleType == 6)//收银员
                {
                    codeIds = permission.CodeIds;
                    if (codeIds.Count() < 1)
                        return GetResult(1, "无关联数据");
                }

                if (storeIds.Count == 0 && !string.IsNullOrEmpty(dto.StoreId))
                    storeIds.Add(dto.StoreId);
                if (codeIds.Count == 0 && !string.IsNullOrEmpty(dto.CodeId))
                    codeIds.Add(dto.CodeId);
            }

            DateTime curDateTime = DateTime.Now.Date;
            var reportFormData = new List<DateTimeRequestDto>();
            reportFormData = Config.GetRecentDays(curDateTime, 1);
            DateTimeRequestDto curReportFormData = reportFormData.FirstOrDefault();

            // 基础查询：限定当日的已支付订单，无跟踪以提升性能
            var baseQuery = _paymentIOC._orderEFCore.QueryAll(d =>
                (string.IsNullOrEmpty(dto.MerchantId) || d.MerchantId.Contains(dto.MerchantId)) &&
                (!storeIds.Any() || storeIds.Contains(d.StoreId)) &&
                (!codeIds.Any() || codeIds.Contains(d.CodeId)) &&
                (d.CreationTime >= curReportFormData.StartTime && d.CreationTime <= curReportFormData.EndTime) &&
                d.PaymentStatus == 1
            ).AsNoTracking();

            // 一次性在数据库端完成金额与数量的聚合统计
            var agg = await baseQuery
                .GroupBy(_ => 1)  // 全局聚合所有记录
                .Select(g => new
                {
                    TodayTurnover = (long)g.Sum(x => x.PayAmount) - (long)g.Sum(x => x.TotalRefundAmount),
                    TodayTurnoverCount = g.Count(),

                    RefundAmount = (long)g.Sum(x => x.TotalRefundAmount),
                    RefundAmountCount = g.Sum(x => x.RefundStatus == 1 ? 1 : 0),

                    DirectRevenue = (long)g.Sum(x => (string.IsNullOrEmpty(x.CouponInstanceId) && string.IsNullOrEmpty(x.DividedAgreementId)) ? x.PayAmount : 0),
                    DirectRevenueCount = g.Sum(x => (string.IsNullOrEmpty(x.CouponInstanceId) && string.IsNullOrEmpty(x.DividedAgreementId)) ? 1 : 0),

                    CooperativeRevenue = (long)g.Sum(x => (string.IsNullOrEmpty(x.CouponInstanceId) && !string.IsNullOrEmpty(x.DividedAgreementId)) ? x.PayAmount : 0),
                    CooperativeRevenueCount = g.Sum(x => (string.IsNullOrEmpty(x.CouponInstanceId) && !string.IsNullOrEmpty(x.DividedAgreementId)) ? 1 : 0),

                    DiscountedRevenue = (long)g.Sum(x => (!string.IsNullOrEmpty(x.CouponInstanceId) && string.IsNullOrEmpty(x.DividedAgreementId)) ? x.PayAmount : 0),
                    DiscountedRevenueCount = g.Sum(x => (!string.IsNullOrEmpty(x.CouponInstanceId) && string.IsNullOrEmpty(x.DividedAgreementId)) ? 1 : 0),

                    CooperativeDiscountedRevenue = (long)g.Sum(x => (!string.IsNullOrEmpty(x.CouponInstanceId) && !string.IsNullOrEmpty(x.DividedAgreementId)) ? x.PayAmount : 0),
                    CooperativeDiscountedRevenueCount = g.Sum(x => (!string.IsNullOrEmpty(x.CouponInstanceId) && !string.IsNullOrEmpty(x.DividedAgreementId)) ? 1 : 0),
                })
                .FirstOrDefaultAsync() ?? new
                {
                    TodayTurnover = 0L,
                    TodayTurnoverCount = 0,

                    RefundAmount = 0L,
                    RefundAmountCount = 0,

                    DirectRevenue = 0L,
                    DirectRevenueCount = 0,

                    CooperativeRevenue = 0L,
                    CooperativeRevenueCount = 0,

                    DiscountedRevenue = 0L,
                    DiscountedRevenueCount = 0,

                    CooperativeDiscountedRevenue = 0L,
                    CooperativeDiscountedRevenueCount = 0,
                };

            // 顾客数单独统计：OpenId 优先，否则 BuyerId；去除空值后做 Distinct
            var customerCount = await baseQuery
                .Select(x => string.IsNullOrEmpty(x.OpenId) ? x.BuyerId : x.OpenId)
                .Where(id => !string.IsNullOrEmpty(id))
                .Distinct()
                .CountAsync();

            var data = new TodayTurnoverRequestDto
            {
                TodayTurnover = agg.TodayTurnover,
                TodayTurnoverCount = agg.TodayTurnoverCount,

                RefundAmount = agg.RefundAmount,
                RefundAmountCount = agg.RefundAmountCount,

                CustomerCount = customerCount,

                DirectRevenue = agg.DirectRevenue,
                DirectRevenueCount = agg.DirectRevenueCount,

                CooperativeRevenue = agg.CooperativeRevenue,
                CooperativeRevenueCount = agg.CooperativeRevenueCount,

                DiscountedRevenue = agg.DiscountedRevenue,
                DiscountedRevenueCount = agg.DiscountedRevenueCount,

                CooperativeDiscountedRevenue = agg.CooperativeDiscountedRevenue,
                CooperativeDiscountedRevenueCount = agg.CooperativeDiscountedRevenueCount,
            };

            //var orders = await _paymentIOC._orderEFCore.QueryAll(d => (string.IsNullOrEmpty(dto.MerchantId) || d.MerchantId.Contains(dto.MerchantId))
            //    && (!storeIds.Any() || storeIds.Contains(d.StoreId))
            //    && (!codeIds.Any() || codeIds.Contains(d.CodeId))
            //    && (d.CreationTime >= curReportFormData.StartTime && d.CreationTime <= curReportFormData.EndTime)
            //    && d.PaymentStatus == 1).Select(d => new OrderResponseDto()
            //    {
            //        Id = d.Id,
            //        MerchantId = d.MerchantId,
            //        StoreId = d.StoreId,
            //        PayAmount = (long)d.PayAmount,
            //        PaymentStatus = (int)d.PaymentStatus,
            //        RefundStatus = (int)d.RefundStatus,
            //        UserId = d.UserId,
            //        CodeId = d.CodeId,
            //        CouponInstanceId = d.CouponInstanceId,
            //        TotalRefundAmount = d.TotalRefundAmount,
            //        DividedAgreementId = d.DividedAgreementId,
            //        OpenId = d.OpenId,
            //        BuyerId = d.BuyerId,
            //    }).ToListAsync();

            //var data = new TodayTurnoverRequestDto();
            //data.TodayTurnover = (long)orders.Sum(x => x.PayAmount) - (long)orders.Sum(x => x.TotalRefundAmount);//(long)orders.Sum(d => d.PayAmount);
            //data.TodayTurnoverCount = orders.Count(d => d.PaymentStatus == 1);


            //data.RefundAmount = (long)orders.Sum(d => d.TotalRefundAmount);
            //data.RefundAmountCount = orders.Count(d => d.RefundStatus == 1);

            //// 统一顾客ID去重：OpenId 优先，否则 BuyerId
            //data.CustomerCount = orders.Select(x => string.IsNullOrEmpty(x.OpenId) ? x.BuyerId : x.OpenId).Where(id => !string.IsNullOrEmpty(id)).Distinct().Count();

            //data.DirectRevenue = (long)orders.Where(d => string.IsNullOrEmpty(d.CouponInstanceId) && string.IsNullOrEmpty(d.DividedAgreementId)).Sum(d => d.PayAmount);
            //data.DirectRevenueCount = orders.Where(d => string.IsNullOrEmpty(d.CouponInstanceId) && string.IsNullOrEmpty(d.DividedAgreementId)).Count();
            //data.CooperativeRevenue = (long)orders.Where(d => string.IsNullOrEmpty(d.CouponInstanceId) && !string.IsNullOrEmpty(d.DividedAgreementId)).Sum(d => d.PayAmount);
            //data.CooperativeRevenueCount = orders.Where(d => string.IsNullOrEmpty(d.CouponInstanceId) && !string.IsNullOrEmpty(d.DividedAgreementId)).Count();
            //data.DiscountedRevenue = (long)orders.Where(d => !string.IsNullOrEmpty(d.CouponInstanceId) && string.IsNullOrEmpty(d.DividedAgreementId)).Sum(d => d.PayAmount);
            //data.DiscountedRevenueCount = orders.Where(d => !string.IsNullOrEmpty(d.CouponInstanceId) && string.IsNullOrEmpty(d.DividedAgreementId)).Count();
            //data.CooperativeDiscountedRevenue = (long)orders.Where(d => !string.IsNullOrEmpty(d.CouponInstanceId) && !string.IsNullOrEmpty(d.DividedAgreementId)).Sum(d => d.PayAmount);
            //data.CooperativeDiscountedRevenueCount = orders.Where(d => !string.IsNullOrEmpty(d.CouponInstanceId) && !string.IsNullOrEmpty(d.DividedAgreementId)).Count();


            return GetResult(1, data: data);

        }

        /// <summary>
        /// 获取平台首页数据
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetPlatformHomepageAsync(DateTime dateTime)
        {
            var orders = await _paymentIOC._orderEFCore.QueryAll(d => d.PaymentStatus == 1
            && d.RefundStatus != 2
            //&& d.CreationTime >= dateTime.Date && d.CreationTime <= dateTime.Date.AddDays(1).AddSeconds(-1)
            )
                .AsNoTracking()
                .GroupBy(_ => 1)  // 全局聚合所有记录
                .Select(d => new
                {
                    Commission = (long)d.Sum(x => x.Commission) - (long)d.Sum(x => x.ProcedureFee),
                    PlatformServiceFee = (long)d.Sum(x => x.PlatformServiceFee) - -(long)d.Sum(x => x.RecommendationCommissionAmount),

                }).FirstOrDefaultAsync() ?? new
                {
                    Commission = 0L,
                    PlatformServiceFee = 0L,
                };

            var withdrawals = await _paymentIOC._withdrawalRecordEFCore.QueryAll(d => d.WithdrawalStatus == 1).AsNoTracking()
                .GroupBy(_ => 1)  // 全局聚合所有记录
                .Select(d => new
                {
                    WithdrawalFee = (long)d.Sum(x => x.Fee - 20L),
                }).FirstOrDefaultAsync() ?? new
                {
                    WithdrawalFee = 0L,
                };

            var sumAmount = orders.Commission + orders.PlatformServiceFee + withdrawals.WithdrawalFee;

            return GetResult(1, data: new
            {
                orders.Commission,
                orders.PlatformServiceFee,
                withdrawals.WithdrawalFee,
                sumAmount
            });
        }

        /// <summary>
        /// 新增订单模拟数据（仅自动运行脚本可用）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddOrdersSimulationAsync(OrderCreateRequestDto dto)
        {
            try
            {
                await _unitOfWork.BeginTransactionAsync(System.Data.IsolationLevel.ReadCommitted);

                OrderRequestDto orderDto = new OrderRequestDto();
                orderDto.OrderAmount = dto.OrderAmount;
                orderDto.CodeId = dto.CodeId;
                orderDto.CouponInstanceId = dto.CouponInstanceId;

                string orderId = Config.GUID();

                if (!string.IsNullOrEmpty(orderDto.CouponInstanceId))
                {
                    string userId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                    orderDto.UserId = userId;
                    //var couponConsumptionRecordResult = await _couponService.AddCouponConsumptionRecordAsync(new Infrastructure.Dto.Request.Coupon.CouponConsumptionRecordRequestDto
                    //{
                    //    CouponInstanceId = orderDto.CouponInstanceId,
                    //    OrderId = orderId,
                    //    UserId = userId,
                    //    ConsumptionType = 3,
                    //    ConsumptionCodeId = orderDto.CodeId,
                    //});

                    var calculateCouponInstanceResult = await _couponService.CalculateCouponInstanceAsync(new Infrastructure.Dto.Request.Coupon.CalculateCouponInstanceRequestDto
                    {
                        CouponInstanceId = orderDto.CouponInstanceId,
                        OrderAmount = orderDto.OrderAmount
                    });

                    //if (couponConsumptionRecordResult.code == ApiCode.fail || calculateCouponInstanceResult.code == ApiCode.fail)
                    //{
                    //    return GetResult(message: "优惠券核销失败，请稍后重试！");
                    //}

                    var calculateCouponInstance = calculateCouponInstanceResult.data as Infrastructure.Dto.Request.Coupon.CalculateCouponInstanceRequestDto;
                    if (calculateCouponInstance != null)
                    {
                        orderDto.DiscountAmount = calculateCouponInstance.DiscountAmount;
                        orderDto.PayAmount = calculateCouponInstance.PayAmount;
                        orderDto.PlatformServiceFee = calculateCouponInstance.PlatformServiceFee;
                        orderDto.PlatformServiceFeeRate = calculateCouponInstance.PlatformServiceFeeRate;
                        orderDto.RecommendationCommissionAmount = calculateCouponInstance.RecommendationCommissionAmount;
                        orderDto.RecommendMerchantId = calculateCouponInstance.RecommendMerchantId;
                    }
                    else
                    {
                        return GetResult(message: "优惠券核销失败，请稍后重试！");
                    }
                }
                else
                {
                    orderDto.PayAmount = orderDto.OrderAmount;
                }

                // 如果实际收款金额小于等于0，则设置为0，并且平台服务费和推荐商户抽成金额也设置为0
                if (orderDto.PayAmount <= 0)
                {
                    orderDto.PayAmount = 0;
                    orderDto.PlatformServiceFee = 0;
                    orderDto.RecommendationCommissionAmount = 0;
                }

                var paymentCode = await _paymentIOC._paymentCodeEFCore.QueryAll(d => d.Id == orderDto.CodeId).FirstOrDefaultAsync();

                Order order = new Order()
                {
                    Id = orderId,
                    OrderCode = Config.GenerateCode("ORD"),
                    OrderType = orderDto.OrderType,
                    CodeId = paymentCode.Id,
                    MerchantId = paymentCode.MerchantId,
                    StoreId = paymentCode.StoreId,
                    UserId = orderDto.UserId,
                    DividedAgreementId = paymentCode.DividedAgreementId,

                    OrderAmount = orderDto.OrderAmount,
                    CouponInstanceId = orderDto.CouponInstanceId,
                    DiscountAmount = orderDto.DiscountAmount,
                    PayAmount = orderDto.PayAmount,
                    PlatformServiceFee = orderDto.PlatformServiceFee,
                    PlatformServiceFeeRate = orderDto.PlatformServiceFeeRate,
                    Rate = 0.0035m,
                    RefundableAmount = orderDto.PayAmount,

                    CreationTime = DateTime.Now,
                    RecommendationCommissionAmount = orderDto.RecommendationCommissionAmount,
                    RecommendMerchantId = orderDto.RecommendMerchantId,

                };

                // 计算手续费（订单金额少于100分即1元RMB就不收取手续费或使用优惠券不收手续费）
                if (string.IsNullOrEmpty(orderDto.CouponInstanceId))
                    order.Commission = (long)(order.PayAmount < 100 ? 0 : Math.Ceiling((decimal)(order.PayAmount * order.Rate)));
                //计算结算金额
                order.SettlementAmount = order.PayAmount - order.Commission - orderDto.PlatformServiceFee;

                //计算结算日期
                int settlementCycle = 0;

                var store = await _paymentIOC._storeEFCore.QueryAll(d => d.Id == paymentCode.StoreId).FirstOrDefaultAsync();
                var merchant = await _paymentIOC._merchantEFCore.QueryAll(d => d.Id == paymentCode.MerchantId).FirstOrDefaultAsync();
                // 1. 首先查找收款码的结算周期
                if (paymentCode.SettlementCycle.HasValue && paymentCode.SettlementCycle.Value > 0)
                {
                    settlementCycle = paymentCode.SettlementCycle.Value;
                }
                else
                {
                    // 2. 如果收款码结算周期为0或null，查找门店的结算周期
                    if (store?.SettlementCycle.HasValue == true && store.SettlementCycle.Value > 0)
                    {
                        settlementCycle = store.SettlementCycle.Value;
                    }
                    else
                    {
                        // 3. 如果门店结算周期为0或null，查找商户的结算周期
                        if (merchant != null)
                        {
                            settlementCycle = merchant.SettlementCycle;
                        }
                    }
                }

                // 计算结算日期：当前时间 + 结算周期天数，只取日期部分
                order.SettlementDate = DateTime.Now.AddDays(settlementCycle).Date;

                //计算分账日期
                DividedAgreement dividedAgreement = null;
                //OrderSnapshotModel orderSnapshotModel= new OrderSnapshotModel();
                if (!string.IsNullOrEmpty(order.DividedAgreementId))
                {
                    dividedAgreement = await _paymentIOC._dividedAgreementEFCore.QueryAll(d => d.Id == order.DividedAgreementId).FirstOrDefaultAsync();
                    if (dividedAgreement?.DividedCycle.HasValue == true)
                    {
                        // 分账日期 = 结算日期 + 分账周期天数，只取日期部分
                        order.DividedDate = order.SettlementDate.AddDays(dividedAgreement.DividedCycle.Value).Date;
                    }
                    var dividedAgreementDetails = await _paymentIOC._dividedAgreementDetailEFCore.QueryAll(d => d.DividedAgreementId == order.DividedAgreementId).ToListAsync();
                    var user = await _paymentIOC._sysUserEFCore.QueryAll(d => dividedAgreementDetails.Select(e => e.UserId).Contains(d.Id)).ToListAsync();

                    //分账收入进入商户主分账余额
                    await AddAccountTransactionAsync(new AccountTransactionRequestDto
                    {
                        UserId = merchant.CreatorId,
                        Amount = order.SettlementAmount,
                        OrderId = order.Id,
                        TransactionType = 1,
                        BalanceType = 5
                    }, false);

                    foreach (var dividedAgreementDetail in dividedAgreementDetails)
                    {
                        orderDto.OrderSnapshot.AgreementDetails.Add(new AgreementDetail
                        {
                            Name = user.Where(e => e.Id == dividedAgreementDetail.UserId).Select(e => e.Name).FirstOrDefault(),
                            Phone = user.Where(e => e.Id == dividedAgreementDetail.UserId).Select(e => e.Phone).FirstOrDefault(),
                            Ratio = dividedAgreementDetail.Ratio,
                        });
                    }
                }
                else
                {
                    //直接营收划入未结算余额
                    await AddAccountTransactionAsync(new AccountTransactionRequestDto
                    {
                        UserId = merchant.CreatorId,
                        Amount = order.SettlementAmount,
                        OrderId = order.Id,
                        TransactionType = 4,
                        BalanceType = 4
                    }, false);
                }


                //记录订单快照
                orderDto.OrderSnapshot.Code = paymentCode?.Code;
                orderDto.OrderSnapshot.CodeName = paymentCode?.CodeName;
                orderDto.OrderSnapshot.StoreCode = store?.StoreCode;
                orderDto.OrderSnapshot.StoreName = store?.Name;
                orderDto.OrderSnapshot.MerchantCode = merchant?.MerchantCode;
                orderDto.OrderSnapshot.MerchantName = merchant?.Name;
                orderDto.OrderSnapshot.AgreementCode = dividedAgreement?.AgreementCode;
                orderDto.OrderSnapshot.AgreementName = dividedAgreement?.AgreementName;
                orderDto.OrderSnapshot.DividedCycle = dividedAgreement?.DividedCycle;
                orderDto.OrderSnapshot.SettlementCycle = settlementCycle;
                orderDto.OrderSnapshot.SnapshotTime = DateTime.Now;
                order.OrderSnapshot = Config.SerializeToJson<OrderSnapshotModel>(orderDto.OrderSnapshot);

                //易票联
                var outTradeNo = order.Id;
                string url = "";
                string sentent = "";
                var apiBaseUrl = _configuration["PaymentApi:BaseUrl"];


                if (dto.PayMethod == "6" || dto.PayMethod == "7")
                {
                    url = $"{apiBaseUrl}/api/txs/pay/UnifiedPayment";

                    order.OutTradeNo = outTradeNo;//商户订单号
                    order.NotifyUrl = $"{_configuration["SelfUrl"]}/api/Payment/ProcessPaymentResultNotification";//支付结果通知地址
                    order.Version = "3.0";//版本号
                    order.ClientIp = "";//用户终端IP
                    order.CustomerCode = "562294004495976";// 商户号
                    order.NoCreditCards = "false";// 是否禁用信用卡（花呗不能用）
                    order.AttachData = "attachData";// 商户备注
                    order.PaymentStatus = 0;//支付状态
                    order.PayMethod = dto.PayMethod;//支付方式
                    order.PayCurrency = orderDto.PayCurrency;// 支持币种
                    order.RedirectUrl = dto.RedirectUrl ?? ""; // 支付通知结果前端跳转地址
                    order.AreaInfo = store?.Address ?? merchant?.Address ?? "440100";// orderDto.AreaInfo;//地区信息六位数

                    orderDto.OrderInfo.Id = outTradeNo;//商品订单编号
                    orderDto.OrderInfo.BusinessType = "100001"; // 业务类型
                    orderDto.OrderInfo.GoodsList.Add(new EpaylinksGoods { Amount = orderDto.PayAmount, Name = merchant?.Name, Number = "1" });//商品信息
                    order.OrderInfo = Config.SerializeToJson(orderDto.OrderInfo);

                    DateTime dtNow = DateTime.Now;
                    order.TransactionStartTime = dtNow.ToString("yyyyMMddHHmmss");//开始时间
                    order.TransactionEndTime = dtNow.AddMinutes(30).ToString("yyyyMMddHHmmss");//结束时间

                    order.NonceStr = Config.GenerateRandomKey(32);//随机字符串

                    sentent = "{\"areaInfo\":\"" + order.AreaInfo +
                        "\",\"attachData\":\"" + order.AttachData + "\",\"clientIp\":\"" + order.ClientIp + "\"," +
                        "\"customerCode\":\"" + order.CustomerCode + "\",\"needSplit\":false,\"noCreditCards\":" + order.NoCreditCards + ",\"nonceStr\":\"" + order.NonceStr + "\",\"notifyUrl\":\"" + order.NotifyUrl + "\"," +
                        "\"orderInfo\":" + order.OrderInfo + "," +
                        "\"payAmount\":" + order.PayAmount + ",\"payCurrency\":\"" + order.PayCurrency + "\",\"redirectUrl\":\"" + order.RedirectUrl + "\",\"transactionEndTime\":\"" + order.TransactionEndTime + "\"," +
                        "\"version\":\"" + order.Version + "\",";
                    sentent += "\"outTradeNo\":\"" + order.OutTradeNo + "\",\"transactionStartTime\":\"" + order.TransactionStartTime + "\"}";
                }

                if (dto.PayMethod == "1" || dto.PayMethod == "35")
                {
                    url = $"{apiBaseUrl}/api/txs/pay/WxJSAPIPayment";

                    string userId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                    var userMini = await _paymentIOC._sysUserMiniProgramEFCore.QueryAll(d => d.Id == userId).FirstOrDefaultAsync();
                    if (userMini == null)
                        return GetResult(0, "用户未登录");
                    order.Version = "3.0";//版本号
                    order.OutTradeNo = outTradeNo;//商户订单号
                    order.CustomerCode = "562294004495976";// 商户号
                    order.SubAppId = userMini.AppId;//子商户公众账号ID
                    order.OpenId = userMini.OpenId;
                    order.ClientIp = "";//用户终端IP

                    orderDto.OrderInfo.Id = outTradeNo;//商品订单编号
                    orderDto.OrderInfo.BusinessType = "100001"; // 业务类型
                    orderDto.OrderInfo.GoodsList.Add(new EpaylinksGoods { Amount = orderDto.PayAmount, Name = merchant?.Name, Number = "1" });//商品信息
                    order.OrderInfo = Config.SerializeToJson(orderDto.OrderInfo);

                    order.PaymentStatus = 0;//支付状态
                    order.PayMethod = dto.PayMethod;//支付方式
                    order.PayCurrency = orderDto.PayCurrency;// 支持币种
                    order.NoCreditCards = "false";// 是否禁用信用卡（花呗不能用）
                    order.NotifyUrl = $"{_configuration["SelfUrl"]}/api/Payment/ProcessPaymentResultNotification";//支付结果通知地址
                    order.AttachData = "attachData";// 商户备注
                    //locationToken

                    DateTime dtNow = DateTime.Now;
                    order.TransactionStartTime = dtNow.ToString("yyyyMMddHHmmss");//开始时间
                    order.TransactionEndTime = dtNow.AddMinutes(30).ToString("yyyyMMddHHmmss");//结束时间

                    order.NonceStr = Config.GenerateRandomKey(32);//随机字符串
                    order.AreaInfo = store?.Address ?? merchant?.Address ?? "440100";// orderDto.AreaInfo;//地区信息六位数
                                                                                     //channelMchtNo

                    // 主要字段
                    sentent = "{\"version\":\"" + order.Version + "\",\"outTradeNo\":\"" + order.OutTradeNo + "\",\"customerCode\":\"" + order.CustomerCode + "\"," +
                        "\"appId\":\"" + order.SubAppId + "\",\"openId\":\"" + order.OpenId + "\",\"clientIp\":\"" + order.ClientIp + "\"," +
                        "\"orderInfo\":" + order.OrderInfo + "," +
                        "\"payAmount\":" + order.PayAmount + ",\"payCurrency\":\"" + order.PayCurrency + "\",\"payMethod\":\"" + order.PayMethod + "\"," +
                        "\"noCreditCards\":\"" + order.NoCreditCards + "\",\"notifyUrl\":\"" + order.NotifyUrl + "\"," +
                        "\"attachData\":\"" + order.AttachData + "\",\"transactionStartTime\":\"" + order.TransactionStartTime + "\"," +
                        "\"transactionEndTime\":\"" + order.TransactionEndTime + "\",\"areaInfo\":\"" + order.AreaInfo + "\",\"nonceStr\":\"" + order.NonceStr + "\"}";

                    // 可选字段（类似第1000行的模式）
                    //sentent += "\"locationToken\":\"\",\"channelMchtNo\":\"\",\"extUserInfo\":\"\",\"terminalInfo\":\"\",\"coupons\":\"\"}";

                }

                if (dto.PayMethod == "99")
                {
                    string userId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                    var userMini = await _paymentIOC._sysUserMiniProgramEFCore.QueryAll(d => d.Id == userId).FirstOrDefaultAsync();
                    url = $"{apiBaseUrl}/api/txs/pay/AliJSAPIPayment";

                    order.Version = "3.0";//版本号
                    order.OutTradeNo = outTradeNo;//商户订单号
                    order.CustomerCode = "562294004495976";// 商户号
                    order.ClientIp = "118.196.30.7";//用户终端IP
                    order.BuyerId = userMini.UserId;//dto.BuyerId;//买家的支付宝唯一用户号
                    //order.BuyerLogonId = "0925NHeCm5ZP7AGmFk6QAGasdTDM92xFR7APB0fFhi7NrQf";

                    orderDto.OrderInfo.Id = outTradeNo;//商品订单编号
                    orderDto.OrderInfo.BusinessType = "100001"; // 业务类型
                    orderDto.OrderInfo.GoodsList.Add(new EpaylinksGoods { Amount = orderDto.PayAmount, Name = merchant?.Name, Number = "1" });//商品信息
                    order.OrderInfo = Config.SerializeToJson(orderDto.OrderInfo);

                    //order.payAmount
                    order.PaymentStatus = 0;//支付状态
                    order.PayMethod = dto.PayMethod;//支付方式
                    order.PayCurrency = orderDto.PayCurrency;// 支持币种
                    order.NoCreditCards = "false";// 是否禁用信用卡（花呗不能用）
                    order.NotifyUrl = $"{_configuration["SelfUrl"]}/api/Payment/ProcessPaymentResultNotification";//支付结果通知地址
                    order.AttachData = "attachData";// 商户备注
                    //locationToken

                    DateTime dtNow = DateTime.Now;
                    order.TransactionStartTime = dtNow.ToString("yyyyMMddHHmmss");//开始时间
                    order.TransactionEndTime = dtNow.AddMinutes(30).ToString("yyyyMMddHHmmss");//结束时间

                    order.NonceStr = Config.GenerateRandomKey(32);//随机字符串
                    order.AreaInfo = store?.Address ?? merchant?.Address ?? "440100";// orderDto.AreaInfo;//地区信息六位数

                    sentent = "{\"version\":\"" + order.Version + "\",\"outTradeNo\":\"" + order.OutTradeNo + "\",\"customerCode\":\"" + order.CustomerCode + "\"," +
    "\"clientIp\":\"" + order.ClientIp + "\",\"buyerId\":\"" + order.BuyerId + "\"," +
    "\"orderInfo\":" + order.OrderInfo + "," +
    "\"payAmount\":" + order.PayAmount + ",\"paymentStatus\":" + order.PaymentStatus + ",\"payCurrency\":\"" + order.PayCurrency + "\"," +
    "\"noCreditCards\":\"" + order.NoCreditCards + "\",\"notifyUrl\":\"" + order.NotifyUrl + "\"," +
    "\"attachData\":\"" + order.AttachData + "\",\"transactionStartTime\":\"" + order.TransactionStartTime + "\"," +
    "\"transactionEndTime\":\"" + order.TransactionEndTime + "\",\"nonceStr\":\"" + order.NonceStr + "\",\"areaInfo\":\"" + order.AreaInfo + "\",\"buyerLogonId\":\"" + order.BuyerLogonId + "\"}";
                }

                order.PaymentStatus = 1;
                order.OpenId = orderId;
                //order.SubOpenId = orderId;
                await _paymentIOC._orderEFCore.AddAsync(order);
                var orderResult = await _paymentIOC._orderEFCore.SaveChangesAsync();

                if (orderResult == 0)
                {
                    return GetResult(message: "交易失败，请稍后重试！");
                }

                await _unitOfWork.CommitAsync();
                //scope.Complete();

                //调用易票联接口
                //var result = await epaylinksService.post(sentent, url);
                //var res = Config.DeserializeFromJson<EpaylinksResponseDto>(result);

                //return GetResult(res.ReturnCode == "0000" ? 1 : 0, message: res.ReturnMsg, data: result);
                return GetResult(orderResult);
            }
            catch (Exception ex)
            {
                await _unitOfWork.RollbackAsync();
                throw;
            }
        }

        /// <summary>
        /// 新增订单测试数据，仅测试环境使用（不涉及真实支付）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddOrdersTestAsync(OrderCreateRequestDto dto)
        {
            try
            {
                await _unitOfWork.BeginTransactionAsync(System.Data.IsolationLevel.ReadCommitted);

                OrderRequestDto orderDto = new OrderRequestDto();
                orderDto.OrderAmount = dto.OrderAmount;
                orderDto.CodeId = dto.CodeId;
                orderDto.CouponInstanceId = dto.CouponInstanceId;

                string orderId = Config.GUID();

                if (!string.IsNullOrEmpty(orderDto.CouponInstanceId))
                {
                    string userId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                    orderDto.UserId = userId;
                    var couponConsumptionRecordResult = await _couponService.AddCouponConsumptionRecordAsync(new Infrastructure.Dto.Request.Coupon.CouponConsumptionRecordRequestDto
                    {
                        CouponInstanceId = orderDto.CouponInstanceId,
                        OrderId = orderId,
                        UserId = userId,
                        ConsumptionType = 3,
                        ConsumptionCodeId = orderDto.CodeId,
                    });

                    var calculateCouponInstanceResult = await _couponService.CalculateCouponInstanceAsync(new Infrastructure.Dto.Request.Coupon.CalculateCouponInstanceRequestDto
                    {
                        CouponInstanceId = orderDto.CouponInstanceId,
                        OrderAmount = orderDto.OrderAmount
                    });

                    if (couponConsumptionRecordResult.code == ApiCode.fail || calculateCouponInstanceResult.code == ApiCode.fail)
                    {
                        return GetResult(message: "优惠券核销失败，请稍后重试！");
                    }

                    var calculateCouponInstance = calculateCouponInstanceResult.data as Infrastructure.Dto.Request.Coupon.CalculateCouponInstanceRequestDto;
                    if (calculateCouponInstance != null)
                    {
                        orderDto.DiscountAmount = calculateCouponInstance.DiscountAmount;
                        orderDto.PayAmount = calculateCouponInstance.PayAmount;
                        orderDto.PlatformServiceFee = calculateCouponInstance.PlatformServiceFee;
                        orderDto.PlatformServiceFeeRate = calculateCouponInstance.PlatformServiceFeeRate;
                        orderDto.RecommendationCommissionAmount = calculateCouponInstance.RecommendationCommissionAmount;
                        orderDto.RecommendMerchantId = calculateCouponInstance.RecommendMerchantId;
                    }
                    else
                    {
                        return GetResult(message: "优惠券核销失败，请稍后重试！");
                    }
                }
                else
                {
                    orderDto.PayAmount = orderDto.OrderAmount;
                }

                // 如果实际收款金额小于等于0，则设置为0，并且平台服务费和推荐商户抽成金额也设置为0
                if (orderDto.PayAmount <= 0)
                {
                    orderDto.PayAmount = 0;
                    orderDto.PlatformServiceFee = 0;
                    orderDto.RecommendationCommissionAmount = 0;
                }

                var paymentCode = await _paymentIOC._paymentCodeEFCore.QueryAll(d => d.Id == orderDto.CodeId).FirstOrDefaultAsync();

                Order order = new Order()
                {
                    Id = orderId,
                    OrderCode = Config.GenerateCode("ORD"),
                    OrderType = orderDto.OrderType,
                    CodeId = paymentCode.Id,
                    MerchantId = paymentCode.MerchantId,
                    StoreId = paymentCode.StoreId,
                    UserId = orderDto.UserId,
                    DividedAgreementId = paymentCode.DividedAgreementId,

                    OrderAmount = orderDto.OrderAmount,
                    CouponInstanceId = orderDto.CouponInstanceId,
                    DiscountAmount = orderDto.DiscountAmount,
                    PayAmount = orderDto.PayAmount,
                    PlatformServiceFee = orderDto.PlatformServiceFee,
                    PlatformServiceFeeRate = orderDto.PlatformServiceFeeRate,
                    Rate = 0.0035m,
                    RefundableAmount = orderDto.PayAmount,

                    CreationTime = DateTime.Now,
                    RecommendationCommissionAmount = orderDto.RecommendationCommissionAmount,
                    RecommendMerchantId = orderDto.RecommendMerchantId,

                };

                // 计算手续费（订单金额少于100分即1元RMB就不收取手续费或使用优惠券不收手续费）
                if (string.IsNullOrEmpty(orderDto.CouponInstanceId))
                    order.Commission = (long)(order.PayAmount < 100 ? 0 : Math.Ceiling((decimal)(order.PayAmount * order.Rate)));
                //计算结算金额
                order.SettlementAmount = order.PayAmount - order.Commission - orderDto.PlatformServiceFee;

                //计算结算日期
                int settlementCycle = 0;

                var store = await _paymentIOC._storeEFCore.QueryAll(d => d.Id == paymentCode.StoreId).FirstOrDefaultAsync();
                var merchant = await _paymentIOC._merchantEFCore.QueryAll(d => d.Id == paymentCode.MerchantId).FirstOrDefaultAsync();
                // 1. 首先查找收款码的结算周期
                if (paymentCode.SettlementCycle.HasValue && paymentCode.SettlementCycle.Value > 0)
                {
                    settlementCycle = paymentCode.SettlementCycle.Value;
                }
                else
                {
                    // 2. 如果收款码结算周期为0或null，查找门店的结算周期
                    if (store?.SettlementCycle.HasValue == true && store.SettlementCycle.Value > 0)
                    {
                        settlementCycle = store.SettlementCycle.Value;
                    }
                    else
                    {
                        // 3. 如果门店结算周期为0或null，查找商户的结算周期
                        if (merchant != null)
                        {
                            settlementCycle = merchant.SettlementCycle;
                        }
                    }
                }

                // 计算结算日期：当前时间 + 结算周期天数，只取日期部分
                order.SettlementDate = DateTime.Now.AddDays(settlementCycle).Date;

                //计算分账日期
                DividedAgreement dividedAgreement = null;
                //OrderSnapshotModel orderSnapshotModel= new OrderSnapshotModel();
                if (!string.IsNullOrEmpty(order.DividedAgreementId))
                {
                    dividedAgreement = await _paymentIOC._dividedAgreementEFCore.QueryAll(d => d.Id == order.DividedAgreementId).FirstOrDefaultAsync();
                    if (dividedAgreement?.DividedCycle.HasValue == true)
                    {
                        // 分账日期 = 结算日期 + 分账周期天数，只取日期部分
                        order.DividedDate = order.SettlementDate.AddDays(dividedAgreement.DividedCycle.Value).Date;
                    }
                    var dividedAgreementDetails = await _paymentIOC._dividedAgreementDetailEFCore.QueryAll(d => d.DividedAgreementId == order.DividedAgreementId).ToListAsync();
                    var user = await _paymentIOC._sysUserEFCore.QueryAll(d => dividedAgreementDetails.Select(e => e.UserId).Contains(d.Id)).ToListAsync();

                    //分账收入进入商户主分账余额
                    await AddAccountTransactionAsync(new AccountTransactionRequestDto
                    {
                        UserId = merchant.CreatorId,
                        Amount = order.SettlementAmount,
                        OrderId = order.Id,
                        TransactionType = 1,
                        BalanceType = 5
                    }, false);

                    foreach (var dividedAgreementDetail in dividedAgreementDetails)
                    {
                        orderDto.OrderSnapshot.AgreementDetails.Add(new AgreementDetail
                        {
                            Name = user.Where(e => e.Id == dividedAgreementDetail.UserId).Select(e => e.Name).FirstOrDefault(),
                            Phone = user.Where(e => e.Id == dividedAgreementDetail.UserId).Select(e => e.Phone).FirstOrDefault(),
                            Ratio = dividedAgreementDetail.Ratio,
                        });
                    }
                }
                else
                {
                    //直接营收划入未结算余额
                    await AddAccountTransactionAsync(new AccountTransactionRequestDto
                    {
                        UserId = merchant.CreatorId,
                        Amount = order.SettlementAmount,
                        OrderId = order.Id,
                        TransactionType = 4,
                        BalanceType = 4
                    }, false);
                }


                //记录订单快照
                orderDto.OrderSnapshot.Code = paymentCode?.Code;
                orderDto.OrderSnapshot.CodeName = paymentCode?.CodeName;
                orderDto.OrderSnapshot.StoreCode = store?.StoreCode;
                orderDto.OrderSnapshot.StoreName = store?.Name;
                orderDto.OrderSnapshot.MerchantCode = merchant?.MerchantCode;
                orderDto.OrderSnapshot.MerchantName = merchant?.Name;
                orderDto.OrderSnapshot.AgreementCode = dividedAgreement?.AgreementCode;
                orderDto.OrderSnapshot.AgreementName = dividedAgreement?.AgreementName;
                orderDto.OrderSnapshot.DividedCycle = dividedAgreement?.DividedCycle;
                orderDto.OrderSnapshot.SettlementCycle = settlementCycle;
                orderDto.OrderSnapshot.SnapshotTime = DateTime.Now;
                order.OrderSnapshot = Config.SerializeToJson<OrderSnapshotModel>(orderDto.OrderSnapshot);

                //易票联
                var outTradeNo = order.Id;
                string url = "";
                string sentent = "";
                var apiBaseUrl = _configuration["PaymentApi:BaseUrl"];


                if (dto.PayMethod == "6" || dto.PayMethod == "7")
                {
                    url = $"{apiBaseUrl}/api/txs/pay/UnifiedPayment";

                    order.OutTradeNo = outTradeNo;//商户订单号
                    order.NotifyUrl = $"{_configuration["SelfUrl"]}/api/Payment/ProcessPaymentResultNotification";//支付结果通知地址
                    order.Version = "3.0";//版本号
                    order.ClientIp = "";//用户终端IP
                    order.CustomerCode = "562294004495976";// 商户号
                    order.NoCreditCards = "false";// 是否禁用信用卡（花呗不能用）
                    order.AttachData = "attachData";// 商户备注
                    order.PaymentStatus = 0;//支付状态
                    order.PayMethod = dto.PayMethod;//支付方式
                    order.PayCurrency = orderDto.PayCurrency;// 支持币种
                    order.RedirectUrl = dto.RedirectUrl ?? ""; // 支付通知结果前端跳转地址
                    order.AreaInfo = store?.Address ?? merchant?.Address ?? "440100";// orderDto.AreaInfo;//地区信息六位数

                    orderDto.OrderInfo.Id = outTradeNo;//商品订单编号
                    orderDto.OrderInfo.BusinessType = "100001"; // 业务类型
                    orderDto.OrderInfo.GoodsList.Add(new EpaylinksGoods { Amount = orderDto.PayAmount, Name = merchant?.Name, Number = "1" });//商品信息
                    order.OrderInfo = Config.SerializeToJson(orderDto.OrderInfo);

                    DateTime dtNow = DateTime.Now;
                    order.TransactionStartTime = dtNow.ToString("yyyyMMddHHmmss");//开始时间
                    order.TransactionEndTime = dtNow.AddMinutes(30).ToString("yyyyMMddHHmmss");//结束时间

                    order.NonceStr = Config.GenerateRandomKey(32);//随机字符串

                    sentent = "{\"areaInfo\":\"" + order.AreaInfo +
                        "\",\"attachData\":\"" + order.AttachData + "\",\"clientIp\":\"" + order.ClientIp + "\"," +
                        "\"customerCode\":\"" + order.CustomerCode + "\",\"needSplit\":false,\"noCreditCards\":" + order.NoCreditCards + ",\"nonceStr\":\"" + order.NonceStr + "\",\"notifyUrl\":\"" + order.NotifyUrl + "\"," +
                        "\"orderInfo\":" + order.OrderInfo + "," +
                        "\"payAmount\":" + order.PayAmount + ",\"payCurrency\":\"" + order.PayCurrency + "\",\"redirectUrl\":\"" + order.RedirectUrl + "\",\"transactionEndTime\":\"" + order.TransactionEndTime + "\"," +
                        "\"version\":\"" + order.Version + "\",";
                    sentent += "\"outTradeNo\":\"" + order.OutTradeNo + "\",\"transactionStartTime\":\"" + order.TransactionStartTime + "\"}";
                }

                if (dto.PayMethod == "1" || dto.PayMethod == "35")
                {
                    url = $"{apiBaseUrl}/api/txs/pay/WxJSAPIPayment";

                    string userId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                    var userMini = await _paymentIOC._sysUserMiniProgramEFCore.QueryAll(d => d.Id == userId).FirstOrDefaultAsync();
                    if (userMini == null)
                        return GetResult(0, "用户未登录");
                    order.Version = "3.0";//版本号
                    order.OutTradeNo = outTradeNo;//商户订单号
                    order.CustomerCode = "562294004495976";// 商户号
                    order.SubAppId = userMini.AppId;//子商户公众账号ID
                    order.OpenId = userMini.OpenId;
                    order.ClientIp = "";//用户终端IP

                    orderDto.OrderInfo.Id = outTradeNo;//商品订单编号
                    orderDto.OrderInfo.BusinessType = "100001"; // 业务类型
                    orderDto.OrderInfo.GoodsList.Add(new EpaylinksGoods { Amount = orderDto.PayAmount, Name = merchant?.Name, Number = "1" });//商品信息
                    order.OrderInfo = Config.SerializeToJson(orderDto.OrderInfo);

                    order.PaymentStatus = 0;//支付状态
                    order.PayMethod = dto.PayMethod;//支付方式
                    order.PayCurrency = orderDto.PayCurrency;// 支持币种
                    order.NoCreditCards = "false";// 是否禁用信用卡（花呗不能用）
                    order.NotifyUrl = $"{_configuration["SelfUrl"]}/api/Payment/ProcessPaymentResultNotification";//支付结果通知地址
                    order.AttachData = "attachData";// 商户备注
                    //locationToken

                    DateTime dtNow = DateTime.Now;
                    order.TransactionStartTime = dtNow.ToString("yyyyMMddHHmmss");//开始时间
                    order.TransactionEndTime = dtNow.AddMinutes(30).ToString("yyyyMMddHHmmss");//结束时间

                    order.NonceStr = Config.GenerateRandomKey(32);//随机字符串
                    order.AreaInfo = store?.Address ?? merchant?.Address ?? "440100";// orderDto.AreaInfo;//地区信息六位数
                                                                                     //channelMchtNo

                    // 主要字段
                    sentent = "{\"version\":\"" + order.Version + "\",\"outTradeNo\":\"" + order.OutTradeNo + "\",\"customerCode\":\"" + order.CustomerCode + "\"," +
                        "\"appId\":\"" + order.SubAppId + "\",\"openId\":\"" + order.OpenId + "\",\"clientIp\":\"" + order.ClientIp + "\"," +
                        "\"orderInfo\":" + order.OrderInfo + "," +
                        "\"payAmount\":" + order.PayAmount + ",\"payCurrency\":\"" + order.PayCurrency + "\",\"payMethod\":\"" + order.PayMethod + "\"," +
                        "\"noCreditCards\":\"" + order.NoCreditCards + "\",\"notifyUrl\":\"" + order.NotifyUrl + "\"," +
                        "\"attachData\":\"" + order.AttachData + "\",\"transactionStartTime\":\"" + order.TransactionStartTime + "\"," +
                        "\"transactionEndTime\":\"" + order.TransactionEndTime + "\",\"areaInfo\":\"" + order.AreaInfo + "\",\"nonceStr\":\"" + order.NonceStr + "\"}";

                    // 可选字段（类似第1000行的模式）
                    //sentent += "\"locationToken\":\"\",\"channelMchtNo\":\"\",\"extUserInfo\":\"\",\"terminalInfo\":\"\",\"coupons\":\"\"}";

                }

                if (dto.PayMethod == "99")
                {
                    string userId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                    var userMini = await _paymentIOC._sysUserMiniProgramEFCore.QueryAll(d => d.Id == userId).FirstOrDefaultAsync();
                    url = $"{apiBaseUrl}/api/txs/pay/AliJSAPIPayment";

                    order.Version = "3.0";//版本号
                    order.OutTradeNo = outTradeNo;//商户订单号
                    order.CustomerCode = "562294004495976";// 商户号
                    order.ClientIp = "118.196.30.7";//用户终端IP
                    order.BuyerId = userMini.UserId;//dto.BuyerId;//买家的支付宝唯一用户号
                    //order.BuyerLogonId = "0925NHeCm5ZP7AGmFk6QAGasdTDM92xFR7APB0fFhi7NrQf";

                    orderDto.OrderInfo.Id = outTradeNo;//商品订单编号
                    orderDto.OrderInfo.BusinessType = "100001"; // 业务类型
                    orderDto.OrderInfo.GoodsList.Add(new EpaylinksGoods { Amount = orderDto.PayAmount, Name = merchant?.Name, Number = "1" });//商品信息
                    order.OrderInfo = Config.SerializeToJson(orderDto.OrderInfo);

                    //order.payAmount
                    order.PaymentStatus = 0;//支付状态
                    order.PayMethod = dto.PayMethod;//支付方式
                    order.PayCurrency = orderDto.PayCurrency;// 支持币种
                    order.NoCreditCards = "false";// 是否禁用信用卡（花呗不能用）
                    order.NotifyUrl = $"{_configuration["SelfUrl"]}/api/Payment/ProcessPaymentResultNotification";//支付结果通知地址
                    order.AttachData = "attachData";// 商户备注
                    //locationToken

                    DateTime dtNow = DateTime.Now;
                    order.TransactionStartTime = dtNow.ToString("yyyyMMddHHmmss");//开始时间
                    order.TransactionEndTime = dtNow.AddMinutes(30).ToString("yyyyMMddHHmmss");//结束时间

                    order.NonceStr = Config.GenerateRandomKey(32);//随机字符串
                    order.AreaInfo = store?.Address ?? merchant?.Address ?? "440100";// orderDto.AreaInfo;//地区信息六位数

                    sentent = "{\"version\":\"" + order.Version + "\",\"outTradeNo\":\"" + order.OutTradeNo + "\",\"customerCode\":\"" + order.CustomerCode + "\"," +
    "\"clientIp\":\"" + order.ClientIp + "\",\"buyerId\":\"" + order.BuyerId + "\"," +
    "\"orderInfo\":" + order.OrderInfo + "," +
    "\"payAmount\":" + order.PayAmount + ",\"paymentStatus\":" + order.PaymentStatus + ",\"payCurrency\":\"" + order.PayCurrency + "\"," +
    "\"noCreditCards\":\"" + order.NoCreditCards + "\",\"notifyUrl\":\"" + order.NotifyUrl + "\"," +
    "\"attachData\":\"" + order.AttachData + "\",\"transactionStartTime\":\"" + order.TransactionStartTime + "\"," +
    "\"transactionEndTime\":\"" + order.TransactionEndTime + "\",\"nonceStr\":\"" + order.NonceStr + "\",\"areaInfo\":\"" + order.AreaInfo + "\",\"buyerLogonId\":\"" + order.BuyerLogonId + "\"}";
                }

                order.PaymentStatus = 1;
                await _paymentIOC._orderEFCore.AddAsync(order);
                var orderResult = await _paymentIOC._orderEFCore.SaveChangesAsync();

                if (orderResult == 0)
                {
                    return GetResult(message: "交易失败，请稍后重试！");
                }

                await _unitOfWork.CommitAsync();
                //scope.Complete();

                //调用易票联接口
                //var result = await epaylinksService.post(sentent, url);
                //var res = Config.DeserializeFromJson<EpaylinksResponseDto>(result);

                //return GetResult(res.ReturnCode == "0000" ? 1 : 0, message: res.ReturnMsg, data: result);
                return GetResult(orderResult, data: order.Id);
            }
            catch (Exception ex)
            {
                await _unitOfWork.RollbackAsync();
                throw;
            }
        }
    }
}

